Originally Posted by
Atlantico
Hi, I'm wondering if it is possible to code a program that listens to more than one port at the same time, and be capable of manage several clients at the same time (I pretty sure this is possible, otherwise there wouldn't be online games and things like that)
Of course, silly -- it's called a server! You should decide if you really need to listen at multiple ports tho, since a large number of clients can be connected to a single server on a single port (which would be the normal and easy way).
Technically, a server does not have to maintain multiple connections -- it is a server by virtue of the fact that it can accept() a connection request. Servers can make calls AND answer them; a client can only make them. But a port number is not like a single phone line; it's a single number to which multiple calls can be addressed simultaneously without problem (presuming the server is set up to answer them all). What happens is that each client gets it's own socket, which is part of the server process. This
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int bindsock (int port) {
struct sockaddr_in Me;
int sock;
if ((sock=socket(PF_INET, SOCK_STREAM, 0))<3) perror("socket");
Me.sin_family=AF_INET;
Me.sin_port=htons(port);
Me.sin_addr.s_addr=INADDR_ANY;
/* inet_aton(addrstr,(struct in_addr*)&Me.sin_addr.s_addr) <-- assign address */
memset(&(Me.sin_zero), '\0', 8);
if (bind(sock,(struct sockaddr*)&Me,sizeof(struct sockaddr))==-1) perror("bind");
if (listen(sock,2)!=0) perror("listen");
return sock;
}
int main(int argc, char *argv[]) { /* argv[1] should be a port number */
struct sockaddr_in info;
int SFD=bindsock(atoi(argv[1])), CFD;
socklen_t len=sizeof(struct sockaddr_in); /* beware this detail */
printf("using port %d...\n",atoi(argv[1]));
CFD=accept(SFD,(struct sockaddr*)&info,&len);
printf("accepted connection from %s \n",inet_ntoa(info.sin_addr));
return 0;
}
is the basic server process in C. It's written for linux but if you included the correct headers it should work anywhere. All it does is monitor a port until a client attempts to connect(), which it accepts and then ends.
If you wanted to accept multiple connections, you could do it in a couple of different ways. Notice that the server uses one socket to monitor the port and then assigns a different socket to the accepted connection. All you need to do is create new sockets for each client.
You also need a method to deal with all the connections and monitor the port at (more or less) the same time. That will depend on the specifics of what you're doing. It is possible to do it without forking or threading, in a continuous loop, if you set the all the sockets in non-blocking mode
Code:
fcntl(sock,F_SETFL,O_NONBLOCK);