In socket programming, why doesn't the client bind to an address?

In socket programming, I see that the server is bound to an address containing an IP and port number. Then the steps are listened and accepted (blocking call). I am wondering why the client does not need to communicate with its IP address and port number. In fact, it communicates with the server socket address. After that, the client calls connect () to establish a connection. Later, the client and server can talk to each other. How can a server talk to a client? The client does not communicate with its IP address and port number. How is it possible for the server to contact the client?

+7
linux sockets network-programming
source share
3 answers

Client port number selection is usually done by the kernel. This makes sense, since only the kernel knows which ports are currently in use. However, you can specify the client port yourself , but I think it is difficult for the client program to make sure that the port is free. He can just "try a mistake"

The selection of client IP addresses is usually done by the kernel in consultation with the IP routing tables. You can show and change them using the route command.


You asked how the server can know the IP address of the client. You need to understand TCP / IP in order to answer your question. Read the wiki article. This should be a good starting point.

+4
source share

I am wondering why the client does not need to communicate with its IP address and port number.

Since inside connect () there is an internal bind () if the socket is not yet bound, and because the server doesnโ€™t care what the client port number is: it does not need to be fixed as the server port number.

In fact, it communicates with the server socket address.

No, it does not connect to the server.

How can a server talk to a client?

On the established connection.

The client does not communicate with its IP address and port number.

Yes, see above.

How is it possible for the server to contact the client?

The same as the client reaching the server. By sending a packet with the destination address and port.

+3
source share

This is because the client always has to connect to the server. The client can be called as a slave, and the server is always the master. But the server can talk with the client only if there is certain code with such a buffered input stream. Otherwise, it cannot send any data to the client, even if there is a connection. The port number is basically the address of the program stored on the server. therefore, when a client-side program has to access the server side, it needs a port number, so the server side does not need the client port number, since the client program itself wants to access the server program.

-one
source share

All Articles