openframeworks/openFrameworks — Issue #866: Multicast & UDP: Local IP required when dealing with multiple network interfaces
Author: urshofer
Created: 2012-01-07 15:38:14+00:00
State: open

Hi -

when it comes down to multicast communication over udp, it's is important that the correct ip address of the local interface is set. Most computers nowadays have several interfaces (wired and wireless). Whereas ofxUDPManager::BindMcast uses INADDR_ANY as the local address, this might be wrong if you are not using the default interface. In my case, I connect the computers in a local wlan. The wlan device is not the primary device on my machine.

Therefore I rewrote the BindMcast function adding a third argument pLocal, the local Ip address of the network interface.

```c++
bool ofxUDPManager::BindMcast(char *pMcast, unsigned short usPort, char *pLocal)
```
changing the line:

```c++
mreq.imr_interface.s_addr = pLocal == "" ? INADDR_ANY: inet_addr(pLocal);
```

which makes a different header file as well:

```c++
bool BindMcast(char *pMcast, unsigned short usPort, char *pLocal = "");
```

As you can see, the pLocal Adress is optional, if omitted, INADDR_ANY is used (backwards compatibility).

NOTE:

I've added the function:

```c++
char* GetInterfaceAddr(const char* interface); //returns the IP of a specified interface
```

to the ofxUDPManager as well. This function returns the IP adress of an interface (e.g. en1 on a mac for the airport device). This is useful in dhcp networks, where your own address always changes. The function itself looks like:

```c++
//--------------------------------------------------------------------------------
char* ofxUDPManager::GetInterfaceAddr(const char* interface)
{
int fd;
struct ifreq ifr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name, interface, IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
return(inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
}
```

Please not that for this function, additional headers have to be included in ofxUDPManager.h:

```c++
#include
```

If you consider the changes useful, theres a copy of the two files downloadable here:
http://dl.dropbox.com/u/394122/ofxUDPManager_uh_07012012.zip

regards,
Urs Hofer