Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connect : connection refused in c program at client side

Tags:

c

sockets

I am using the following code to connect to the server at a certain port which are provided as command line arguments ...

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <stdlib.h>
#include <strings.h>

int main(int argc,char *argv[])
{
   struct sockaddr_in serverAddr;
   int clientSocketFd ;
   char buffer[1024];

 if((clientSocketFd = socket(AF_INET, SOCK_STREAM, 0))==-1)
    perror("socket");

//get the server IP address and PORT
bzero(&serverAddr, sizeof serverAddr);
printf("ip address :- %s\n",argv[1]);
inet_pton(AF_INET, argv[1], &(serverAddr.sin_addr));
serverAddr.sin_family=AF_INET;
serverAddr.sin_port = atoi(argv[2]);

printf("PORT :- %d\n",serverAddr.sin_port);
//connect to server
if(connect(clientSocketFd,(struct sockaddr *) &serverAddr, sizeof(serverAddr)) == -1)
    perror("connect");

printf("Connecting to the server %s on port %s \n",argv[1],argv[2]);

while (1)
{
    //receive incoming data
    if(recv(clientSocketFd, buffer,1023, 0)==-1)
    {
    printf("buffer : %s\n" ,buffer);
    printf("Received from Server : %s \n",buffer);
        break;
    }


}
close(clientSocketFd);

}

but at the client side , it shows "connect : Connection Refused"...

If I use telnet , then it shows connected , but not able to connect through the above code of client.c plz help

Also I changed the number of maximum allowed pending connections to 100 , then also the problem did not solved... :( ...help plz

like image 589
Subbu Avatar asked Dec 03 '25 17:12

Subbu


1 Answers

You are connecting to the wrong port. Change:

serverAddr.sin_port = atoi(argv[2]);

To:

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

Think of these structures as being used to communicate with another planet where they write their numbers differently. You have to convert to and from the way you write numbers to the way they write numbers, otherwise you get nonsense.

The htons function converts ports numbers from the way your computer stores them to the way they are used on the network. The ntohs function converts port numbers from the way they are used on the network to the way your computer stores them. Socket addresses are in network byte order.

like image 118
David Schwartz Avatar answered Dec 06 '25 08:12

David Schwartz