gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:50:10 24 4
gpt4 key购买 nike

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

无用服务器.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);

解决了这个问题。谢谢!

最佳答案

What am I doing wrong?

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

    server_addr.sin_port = htons(50000);

关于python - C 服务器 - Python 客户端。连接被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62772314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com