C server - Python client. connection refused
Anton Zakharov:
I'm new to Socket, please forgive me for my complete ignorance.
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 is compiled with gcc. Then, I run the server in a terminal. The client is called by 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 try to connect to the C server from the C client, everything is fine. I use AF_INET, SOCK_STREAM in both cases.
When I try to connect to the analogy Python server from a Python client, everything is fine.
What am I doing wrong?
renew.
replace
server_addr.sin_port = 50000;
and
server_addr.sin_port = htons(50000);
solved the problem. Thanks!
animal:
What am I doing wrong?
In your 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);