简体   繁体   English

C 服务器 - Python 客户端。 拒绝连接

[英]C server - Python client. Connection refused

I'm new to Sockets, please excuse my complete lack of understanding.我是 Sockets 的新手,请原谅我完全不了解。

useless_server.c: 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无用客户端.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. useless_server.c 是用 gcc 编译的。 Then I run server in one terminal.然后我在一个终端上运行服务器。 Client is called from another.客户端是从另一个调用的。

When running useless_client.py I get:运行 useless_client.py 时,我得到:

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.当我尝试从 C 客户端连接到 C 服务器时 - 一切都很好。 I use in both cases AF_INET, SOCK_STREAM.我在这两种情况下都使用 AF_INET、SOCK_STREAM。

When I am trying to connect from Python client to analogical Python server - everything is fine.当我尝试从 Python 客户端连接到模拟 Python 服务器时 - 一切都很好。

What am I doing wrong?我究竟做错了什么?

Updated.更新。

replacing更换

server_addr.sin_port = 50000;

with

server_addr.sin_port = htons(50000);

fixed the problem.解决了这个问题。 Thanks!谢谢!

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):在 C 程序中,您忘记将端口号转换为网络字节顺序(在 Python 中隐式完成):

    server_addr.sin_port = htons(50000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM