【问题标题】:C server - Python client. Connection refusedC 服务器 - Python 客户端。拒绝连接
【发布时间】:2020-10-27 12:53:29
【问题描述】:

我是 Sockets 新手,请原谅我完全不了解。

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 是用 gcc 编译的。 然后我在一个终端上运行服务器。客户端被另一个调用。

运行 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

当我尝试从 C 客户端连接到 C 服务器时 - 一切都很好。 我在这两种情况下都使用 AF_INET、SOCK_STREAM。

当我尝试从 Python 客户端连接到类比 Python 服务器时 - 一切都很好。

我做错了什么?

已更新。

替换

server_addr.sin_port = 50000;

server_addr.sin_port = htons(50000);

解决了这个问题。谢谢!

【问题讨论】:

    标签: python c sockets


    【解决方案1】:

    我做错了什么?

    在 C 程序中,您忘记将端口号转换为网络字节顺序(在 Python 中隐式完成):

        server_addr.sin_port = htons(50000);
    

    【讨论】:

    • 哇!非常感谢!我也是 C 新手,所以犯了很多愚蠢的错误。
    猜你喜欢
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    相关资源
    最近更新 更多