C server - Python client. Connection refused

Viewed 72

I'm new to Sockets, please excuse my complete lack of understanding.

useless_server.c:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>


int main(void)
{
    int sd;
    int newsd;
    struct sockaddr_in client_addr;
    socklen_t cli_size;
    struct sockaddr_in server_addr;

    sd = socket(AF_INET, SOCK_STREAM, 0);
    if (sd < 0)
    {
        printf("unable to create socket\n");
        exit(1);
    }

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = 50000;

    if (bind(sd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0)
    {
        printf("unable to bind socket\n");
        exit(1);
    }

    listen(sd, 2);

    while (1)
    {
        cli_size = sizeof(client_addr);

        newsd = accept(sd, (struct sockaddr *) &client_addr, &cli_size);
        printf("Got connection from %s\n", inet_ntoa(client_addr.sin_addr));
        if (newsd < 0)
        {
            printf("Unable to accept connection\n");
            exit(1);
        }
        sleep(5);
        close(newsd);
    }

    return 0;
}

useless_client.py

#!/usr/bin/env python3

import socket


sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
sock.connect((socket.gethostname(), 50000))

useless_server.c was compiled with gcc. Then I run server in one terminal. Client is called from another.

When running useless_client.py I get:

Traceback (most recent call last):
  File "./useless_client.py", line 7, in <module>
    sock.connect((socket.gethostname(), 50000))
ConnectionRefusedError: [Errno 111] Connection refused

When I am trying to connect to the C server from C client - everything is fine. I use in both cases AF_INET, SOCK_STREAM.

When I am trying to connect from Python client to analogical Python server - everything is fine.

What am I doing wrong?

Updated.

replacing

server_addr.sin_port = 50000;

with

server_addr.sin_port = htons(50000);

fixed the problem. Thanks!

1 Answers

What am I doing wrong?

In the C program, you forgot to convert the port number to network byte order (which is done implicitly in Python):

    server_addr.sin_port = htons(50000);
Related