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.
hek2mgl
source share