Local Host Server Socket Program not working

A Mohammed Junaid picture A Mohammed Junaid · Apr 12, 2013 · Viewed 8.1k times · Source

I have server and client socket programs written in C. I want to connect the client program with server program on my laptop using local host ipaddress 127.0.0.1. When i execute the server program. its output is binding failed and stops. How to make this possible that is client connecting to server on the same laptop ie through local host. Please Help.

Here is the Server Code(this is a echo server program):

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

main(int argc, char *argv[])
{
    int clilen, sockfd, newsockfd, n, cpid;
    char msg[100];
    struct sockaddr_in serv_addr, cli;
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("socket failed to establish\n");
        exit(0);
    }
    printf("socket created\n");
    bzero((char *)&serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
    serv_addr.sin_port = htons(atoi(argv[2]));
    if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
        printf("binding failed\n");
        exit(0);
    }
    printf("binding established\n");
    if (listen(sockfd, 5) < 0)
    {
        printf("not listening\n");
        exit(0);
    }
    printf("listening|n");
    for (;;)
    {
        clilen = sizeof(cli);
        if ((newsockfd = accept(sockfd, (struct sockaddr *)&cli, &clilen)) < 0)
        {
            printf("accept failed\n");
            exit(0);
        }
        printf("accepted\n");
        cpid = fork();
        if (cpid == 0)
        {
            n = read(newsockfd, msg, 80);
            msg[n] = '\0';
            write(newsockfd, msg, strlen(msg));
            close(newsockfd);
            exit(0);
        }
    }
}

Answer

Deepu picture Deepu · Apr 12, 2013

I believe the problem has occurred because you have passed wrong values through the command line.

The following line of code may not have worked as you expect,

serv_addr.sin_addr.s_addr=inet_addr(argv[1]);

Please change it to

 servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

Also add this check to test the port number,

unsigned int port;
if ( argc < 2 ) 
{
   port = Some_Port_No;
}
else 
{
   port=atoi(argv[2]);
}

And change

serv_addr.sin_port=htons(atoi(argv[2]));

to

servaddr.sin_port = htons(port);