views:

286

answers:

5

For the following I'm assuming one network card.

I have a component of my program which is designed to let others in the subnet know of its existence. For this, I've implemented a solution where whenever the program starts up (and periodically afterwards) it sends a broadcast to INADDR_BROADCAST - whoever listens on the required port will remember where it came from for later use.

The problem with this is that I don't want to remember my own broadcasts. I thought that in theory this would be easy to do - simply find out the local ip and compare to what you get in recvfrom.

However, I've found it difficult to get the local IP: getaddrinfo with NULL returns 127.0.0.1, getaddrinfo with the hostname returns the public ip. Can anyone point me in the direction of finding the actual subnet ip ? I think I must be missing something very obvious here but well... I'm still missing it :)

Note: I've read other SO questions on broadcasts, in particular this one: http://stackoverflow.com/questions/683624/udp-broadcast-on-all-interfaces but I haven't gotten round to the multiple interface issue yet.

+2  A: 

Well at start-up you could broadcast a different message with random (but tracked) value, then wait for that message, to discover your own address, from then on, you can send normal messages, ignoring your sourced messages.

Simeon Pilgrim
That's a pretty good idea but it is a bit hackish - the information is readily available (ipconfig/ifconfig) so I should be able to extract it somehow
laura
true, you could change it to be a parameter of your application, and then make a scripting issue. I agree it's very hackish
Simeon Pilgrim
Accepting this because, although hacky, is the only way to do it without specific API calls. Plus, I am already transmitting a tracked value, so I just need to add an extra line of code.
laura
+1  A: 

Search for scoket options and see whether these works: IP_MULTICAST_LOOP,IP_BLOCK_SOURCE

Priyank Bolia
A: 

What about RARP/BOOTP?

zaharpopov
+1  A: 

getsockname (function documentation) can discover the local IP address associated with a particular socket. If you call this on the socket you're using to send the broadcast, you should see the same IP address you'll see returned by recvfrom.

LnxPrgr3
Returns `0.0.0.0` on Windows, some strange gibberish on linux.
laura
A: 

On linux, you can get the IP address of a given interface using ioctl with the SIOCGIFADDR option. I don't think this works for Windows, though. For that, you'll have to do something goofy like this.

Andrew