Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call bind() and then connect() on same socket descriptor?

Just a curious question about networking socket programming in a Windows Application with C/C++:

How can I tell the connect() function to use a particular source IP and source port values?

  • After a socket is created, application calls connect() to remote IP and port by using the sockaddr structure.

  • the connect() function internally selects the source IP and port for the connection.

Rather than the system deciding the source IP and/or port for the connect(), let that be the application's responsibility to decide which source IP and/or port to bind to.

like image 748
anup kataria Avatar asked Nov 01 '25 02:11

anup kataria


2 Answers

How can I tell the connect() function to use a particular source IP and source port values?

Use the socket library's bind() function for that. Yes, you can call bind() before connect() for an outgoing socket. That is a perfectly legitimate operation for both UDP and TCP sockets.

like image 131
Remy Lebeau Avatar answered Nov 03 '25 15:11

Remy Lebeau


bind() requests port that is not in use so it can claim it and become a server, while connect() wants a port that is already in use, so it can connect to it and talk to the server.

As user stark said, you need to call bind if you want to specify which interface/port combination to use, although if you want next call to bind it to a random available port number, you can opt out from bind() call because client doesn't necessarily has to have a fixed port number.

It is possible to ask the kernel to select a specific port before calling connect(), but if I may ask - why you wouldn't want to kernel to allocate source ports, as far as I know it's not best practice.

like image 39
Xchg0x5f375d Avatar answered Nov 03 '25 17:11

Xchg0x5f375d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!