Thread: Multiple Ports using Sockets

  1. #1
    Registered User
    Join Date
    Feb 2003

    Multiple Ports using Sockets

    I am looking to create a distributed server that can listen on multiple ports. I have code written that works with one port, but I am not sure how to specify the server to listen on 2 ports. I put my entire code down for the server because it is short. I have been playing with the code for quite some time, but I can't figure anything out. Any help is much appreciated.

    #include <stdio.h>
    #include <sys/types.h> 
    #include <sys/socket.h>
    #include <netinet/in.h>
    void error(char *msg)
    int main(int argc, char *argv[])
         int sockfd, newsockfd, portno, clilen;
         char buffer[256];
         struct sockaddr_in serv_addr, cli_addr;
         int n;
         if (argc < 2) {
             fprintf(stderr,"ERROR, no port provided\n");
         sockfd = socket(AF_INET, SOCK_STREAM, 0);
         if (sockfd < 0) 
            error("ERROR opening socket");
         bzero((char *) &serv_addr, sizeof(serv_addr));
         portno = atoi(argv[1]);
         serv_addr.sin_family = AF_INET;
         serv_addr.sin_addr.s_addr = INADDR_ANY;
         serv_addr.sin_port = htons(portno);
         if (bind(sockfd, (struct sockaddr *) &serv_addr,
                  sizeof(serv_addr)) < 0) 
                  error("ERROR on binding");
         clilen = sizeof(cli_addr);
         newsockfd = accept(sockfd, 
                     (struct sockaddr *) &cli_addr, 
         if (newsockfd < 0) 
              error("ERROR on accept");
         n = read(newsockfd,buffer,255);
         if (n < 0) error("ERROR reading from socket");
         printf("Here is the message: %s\n",buffer);
         n = write(newsockfd,"I got your message",18);
         if (n < 0) error("ERROR writing to socket");
         return 0; 

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    int sockfd,
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    Simple. Use an array of integers, and open a socket for each one, using a different port for each one. Listen on each one. Read from each one. Write to each one. Close each one.

    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. TCP Sockets: multiple clients - one server
    By Printisor in forum C Programming
    Replies: 4
    Last Post: 11-01-2007, 10:34 AM
  2. multiple connections via sockets
    By cope in forum Networking/Device Communication
    Replies: 7
    Last Post: 06-07-2007, 10:35 AM
  3. multiple UDP sockets with select()
    By nkhambal in forum Networking/Device Communication
    Replies: 2
    Last Post: 01-17-2006, 07:36 PM
  4. Replies: 18
    Last Post: 12-05-2003, 12:06 PM
  5. Sockets, Multiple I/O
    By _Cl0wn_ in forum C Programming
    Replies: 3
    Last Post: 03-18-2003, 03:53 PM