Binding to a specific IP address
Binding to a specific IP address
- Subject: Binding to a specific IP address
- From: Christopher Kempke <email@hidden>
- Date: Sat, 16 Dec 2006 14:12:25 -0800
I'm trying to do this using the BSD sockets APIs (so that the code
can be largely reused cross-platform). My app "announces" itself at
startup by broadcasting its IP address as a UDP packet. In this
multihomed world we live in now, I'm trying to deal with the case of
multiple IP addresses.
I've used getifaddrs() to get the list of AF_INET IP addresses on my
machine (I'll worry about v6 another day). Now, I want to bind to
each of those addresses, and send a single broadcast packet with the
IP address to the world (then unbind, since I'll receive on
INADDR_ANY for the main bulk of the application).
Here's what I'm doing for each address (in dotted form as a char *)
sInt16 sockAddrLen = sizeof(SOCKADDR_IN);
SOCKADDR_IN sockAddr2;
sockAddr2.sin_family = AF_INET;
sockAddr2.sin_port = htons(0); // Arbitrary sending port.
sockAddr2.sin_addr.s_addr =inet_addr(address);
TCPEndPointType tempSocket;
tempSocket = socket( AF_INET, SOCK_DGRAM, 0);
if (tempSocket == INVALID_SOCKET)
{... error checking here...}
int boolVal = true;
err = setsockopt(tempSocket, SOL_SOCKET, SO_BROADCAST, &boolVal,
sizeof(int));
err = setsockopt(tempSocket, SOL_SOCKET, SO_REUSEPORT, &boolVal,
sizeof(int));
err = setsockopt(tempSocket, SOL_SOCKET, SO_REUSEADDR, &boolVal,
sizeof(int));
if (err == SOCKET_ERROR)
{...error checking here...}
// Bind it to our address and the specified port (only the sending one)
err = bind(tempSocket, (sockaddr*)&sockAddr2, sockAddrLen);
if (err == SOCKET_ERROR)
{
err = errno;
}
Everything works until the bind, which returns -1 and an errno of 49
(EADDRNOTAVAIL: can't assign requested address). If I replace the
address with INADDR_ANY, the code works.
So far I've tried:
1 - htonl() around the inet_addr() call -- which shouldn't be
required according the the documentation I've seen.
2 - the various setsockopt() calls you see above.
3 - all three of the IP addresses on my machine fail with the same code.
I'm guessing I'm off by something simple. Can anyone give me a hint
what it might be?
--Chris
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Macnetworkprog mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden