I am writing a simple sender and receiver program to transit using UDP so it’s connectionless, but I am having a problem figuring out whether my receiver program needs to call bind() or the server and/or both. My receiver program(client) will sit in an infinite loop waiting to receive data from the sender(server) and then it will print out the data. I’m not quite sure what bind() does exactly besides associating an address/port with a specific socket. Why is it that I need to call bind()?
Share
You need to call
bind(2)so that the OS knows which application to route network packets to. When you callbindwith a specific port for a given protocol (e.g. TCP or UDP), you’re asking it “whenever you see a network packet on port XXXXX, please give it to me”.Say, for example, that two copies of your program were running, and they both wanted to listen for UDP packets on the same port. If they both call
bindon the same port, then one will succeed and one will fail, since the OS can arbitrate who is bound to each port. Then, any packet received on that port will be given to whichever instance of the program succeeded at binding to that port.