Search code examples
cnetwork-programmingposixsystems-programming

Does bind() modify sin_port in C?


Does the bind() function in linux can modify its argument ? I ask this because a sin_port of 0 means that the OS will choose the port, and I would like to get this port after this call.


Solution

  • No, it does not modify the argument. Instead you use getsockname after binding to find out what port you got.

    You can also use getsockname after connect to get both the local port assignment and the local address (if you have more than one address) correspomnding to the route to the remote host. This works even with UDP where connect doesn't actually send any packets and only logically binds addresses.