Search code examples
linuxservertcpbind

How would you code a TCPIP Server application running on Linux to bind to more than port concurrently?


I am curious it there is a way to have a TCP/IP server application bind and listen for connection requests on more than one port concurrently.

A typical server would bind to a IP address / port and listen for connection requests on the bound port and then complete the connection request i.e. 111.111.111.001:3000

What I am wondering is in the Linux world how would you code a TCP/IP server application to bind to more than one port# on the same IP address i.e. 111.111.111.001:3000, 111.111.111.001:3001, 111.111.111.001:3002 and so on and so forth.

Just for clarification I am referring to your run of the mill Linux server, running Debian or Ubuntu.


Solution

  • Bind to each port separately using separate sockets. Use the select, poll, or epoll facilities to check for incoming connections on all sockets at once. Then, once you have been notified that there is an incoming connection, use accept on the appropriate socket to accept it. The same approach can be used for sending to/receiving from multiple sockets.

    Another approach is to use multi threading. Each socket gets its own thread which handles just that socket.

    Both approaches have their own merits and can be combined. Which one to use depends on your use case and programming style.