Is it possible to bind and listen on the same IP address with TCP / IP sockets? (Linux / C)

I have always used:

serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); 

which means that I will accept connections from any interface. If I replaced INADDR_ANY with "192.168.0.1". Does this mean that I will accept connections only from the IP address 192.168.0.1, or does it mean that I will accept connections from the 192.168.0.1 interface ??

I have a situation where I have several clients (each with a unique IP address, but the same port number), trying to connect to the same server. Can I have several listening functions (separate streams) listening on a unique IP address and port? Or should I accept any connection and receive network information after the connection?


Edit To give more clarification.

If I say serv_addr.sin_addr.s_addr = inet_addr ("192.168.0.1") and the client with the IP address 192.168.0.2 tries to connect, will the listen command reject this?

+4
source share
2 answers

The binding address is the local address for listening; you can specify the address of the local interface.

If you want to control who can connect, you can either check the peer address inside the select / accept loop, or restrict incoming connections using iptables.

Update

If I say serv_addr.sin_addr.s_addr = inet_addr ("192.168.0.1") and the client with the IP address 192.168.0.2 tries to connect, will the command reject it? I want to have multiple threads, each serving a unique IP address.

No, the address is the address on the local computer. Given that you are going to use multi-threaded design, I would recommend that you run the listen / accept code in one thread, check the client address, decide which workflow is suitable, and then start it.

At the risk of showing my age, I still prefer to use listen / accept / select for most socket codes - this is a personal thing of taste and, yes, affects design when it comes to locking / non-blocking IO, buffering, etc.

+7
source

If I replaced INADDR_ANY with "192.168.0.1". Does this mean that I accept connections only from the IP address 192.168.0.1 or do I accept connections from the interface 192.168.0.1 located on?

Yes

Now I have a situation where I have several clients (each with a unique IP address, but the same port number), trying to connect to the same server. Can I have several listening functions (separate streams) listening to a unique IP address and port? Or should I accept any connection and get network information after I connected?

Yes. You can β€œdevelop” (that is, create a new thread) for each connection that you want to process, however you will have to do the filtering yourself. There is no way (which I know in the API) to disable this work on the stack.

0
source

All Articles