anup kataria
anup kataria

Reputation: 109

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?

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.

Upvotes: 4

Views: 2689

Answers (3)

Luis Colorado
Luis Colorado

Reputation: 12645

Yes, you can. Indeed there's a reason to do that: In case your routing policy makes your connection to be established from an IP address which is not the one you want to use, you can force in a multihomed/routing host a specific IP address as source by means of bind(2) system call. Another use is to specify a fixed source port for the connection, but this is not as usual as the previous case.

But beware: you can select only one of the already configured IP addresses you have, not any address you can imagine.

Upvotes: 2

Xchg0x5f375d
Xchg0x5f375d

Reputation: 449

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.

Upvotes: 4

Remy Lebeau
Remy Lebeau

Reputation: 595402

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.

Upvotes: 4

Related Questions