I'm trying to write a server-client socket program in C. The objective is for the server to listen on a specific port, but across a range of IP addresses belonging to the same IP subnet. This IP subnet is part of the 127.x.x.x range (not 127.0.0.1 of course).

Couple of points to note:

This is a stream-based socket, and not Datagram sockets.

This is not a broadcast address.

Implementation in C/C++ only on Unix/Linux platform

I do not want to open multiple sockets on the server for each IP address in the range. This is not scalable.

3 Answers
3

You can only bind to one address on a single socket. Why can't you bind to INADDR_ANY and simply reject any packets not bound for your target IPs? Alternatively, you could bind to an arbitrary port and use OS-level magic (e.g. iptables, bpf) to reroute packets destined for those IP/port combinations to your socket.

Thanks for this suggestion. Can you please elaborate on "reject any packets not bound for your target IPs" ? Does this have to be done within my code by inspecting the headers on each incoming packet?
–
vivJun 25 '12 at 5:30

2

@Vivek: No, because it's a stream-based socket - you just need to call getpeername() on the socket returned by accept(), and check that it's one of the addresses you want to use.
–
cafJun 25 '12 at 5:53

Apologize, I misread and thought you were using UDP. caf's suggestion is the right API for a TCP socket.
–
Andy RossJun 25 '12 at 15:28

The socket API does not allow binding to a subnet -- you can bind to one IP or to any IP. You can listen for all inbound connections and reject those that don't apply. If you need to divvy connections out between processes on the same server, use a single listening socket, and transfer incoming connections to the worker processes.

Thanks. In this case, there are no worker processes involved. The requirement stems from an imposed security constraint that the socket must open only on specific IP's. The actual IP address is dynamic in nature. Therefore, instead of dynamically trying to determine which IP to open the socket on, I was checking if a subnet-based approach would work.
–
vivJun 25 '12 at 8:09

If that is, indeed, a security constraint then perhaps your team should revisit that decision and try to figure out exactly what sort of security they think it's buying.
–
tylerlJun 26 '12 at 4:20

You can use a firewall to prevent anyone from outside the desired subnet from connecting (that's at the o/s level). You can put the socket in promiscuous mode and accept all connections on a given interface. I don't know if you can do both (have a socket in promiscuous mode and run iptables on it). Essentially it's like building a packet sniffer that only listens on one port.