cnetwork-programmingudpbroadcastberkeley-sockets

How to ignore your own broadcast udp packets


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: UDP-Broadcast on all interfaces but I haven't gotten round to the multiple interface issue yet.


Solution

  • 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.