Home > Net >  Why is this program timing out without any network traffic?
Why is this program timing out without any network traffic?

Time:06-18

I am trying to create a simple c program that hides the differences between Linux and Windows when making sockets and connecting to servers

The Linux part of this code compiles without any warnings or errors but times out after resolving the host IP and does not connect to the server running (nc -lvnp 7777)

Using tcpdump -i eth0 -v port 7777 to capture all the traffic to and from the machine running the program shows nothing

class Socket
{
    public:
    int initsoc(void);

    int connectsoc(int sock, const char * host, int port);

};

int Socket::connectsoc(int sock, const char * host, int port)
    #ifdef _WIN32
        /* windows part */
    #else

        struct hostent *server;
        struct sockaddr_in server_addr;
        struct in_addr *address;

        server_addr.sin_family = AF_INET;
        server_addr.sin_port = port;

        /* resolve host */
        
        server = gethostbyname(host);
        if (server == NULL)
        {
            printf("Error : %s \nFailed to resolve %s:%d", strerror(errno), host, port);
            return -1;
        }


        address = (struct in_addr *) (server->h_addr);
        printf("Resolved: [%s] ===> [%s]\n", host, inet_ntoa(*address));        
        server_addr.sin_addr.s_addr = inet_addr(inet_ntoa(*address));
        iResult = connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
        printf("Connect returned : %d\n",iResult);
        if (iResult < 0)
        {
            printf("Error: %s\nFailed to connect\n",strerror(errno));
            return -1;
        }
        printf("Connected to [%s:%d]\n",host,port);
        
        return 0;

I tried to open a netcat listener on a machine on the same network as the computer running the program without any NATs but it still times out

this is how i compiled and what it outputs

g   -Wall -ggdb3 -pedantic -g main.cpp  -o app 
Resolved: [10.0.0.100] ===> [10.0.0.100]
Connect returned : -1
Error: Connection timed out
Failed to connect

the ip of the machine running the code is 10.0.0.2

the ip of the machine running the netcat server is 10.0.0.100

CodePudding user response:

As commented by @user253751, this line:

server_addr.sin_port = port;

should be changed to:

server_addr.sin_port = htons(port);

  • Related