Search code examples
csocketstcp

Client unable to bind to the given port and connect to the given server


I need my client to bind to a particular port and then connect to a server. The problem is, if I bind to the given port successfully I am unable to connect to the server. If I don't attempt to bind to the port, I am able to connect to the server.

Below is my program:

int main()
{

    int sock, bytes_recieved;
    char send_data[1024],recv_data[1024];
    struct hostent *host;
    struct sockaddr_in server_addr,client_addr;

    host = gethostbyname("127.0.0.1");

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("Socket");
        exit(1);
    }
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(4000);
    client_addr.sin_addr = *((struct in_addr *)host->h_addr);
    bzero(&(client_addr.sin_zero),8);

    //host = gethostbyname("192.168.61.67");
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(2404);
    server_addr.sin_addr = *((struct in_addr *)host->h_addr);
    bzero(&(server_addr.sin_zero),8);

    if (bind(sock, (struct sockaddr *)&client_addr, sizeof(struct sockaddr))== -1)
    {
        perror("Unable to bind");
        exit(1);
    }
    else
    {
        fprintf(stderr,"Client bound to 4000\n");
    }

    if (connect(sock, (struct sockaddr *)&server_addr,
                sizeof(struct sockaddr)) == -1)
    {
        perror("Connect");
        exit(1);
    }
    else
    {
        printf("Connected to the server\n");
    }

    while(1)
    {

      bytes_recieved=recv(sock,recv_data,1024,0);
      recv_data[bytes_recieved] = '\0';

      if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0)
      {
       close(sock);
       break;
      }

      else
       printf("\nRecieved data = %s " , recv_data);

       printf("\nSEND (q or Q to quit) : ");
       gets(send_data);
        if (strcmp(send_data , "q") != 0 && strcmp(send_data , "Q") != 0)
       send(sock,send_data,strlen(send_data), 0);

      else
      {
       send(sock,send_data,strlen(send_data), 0);
       close(sock);
       break;
      }

    }
return 0;
}

In this program, if I use localhost for both the client and the server, I am able to bind to the port and connect to the server successfully. The problem appears if I give a different IP to the server.

Kindly suggest any changes to the code to achieve my goal.


Solution

  • Your problem is that you are binding to the address 127.0.0.1. This address can only be used to connect to other loopback addresses.

    Instead, you should be setting the sin_addr member of the bound address to INADDR_ANY:

    client_addr.sin_addr.s_addr = INADDR_ANY;