gpt4 book ai didi

当连接到服务器的新端口套接字时,客户端总是被拒绝连接

转载 作者:行者123 更新时间:2023-11-30 17:16:24 25 4
gpt4 key购买 nike

我正在设计一个基于套接字编程的客户端/服务器系统。客户端首先连接到服务器上具有固定端口 Pa 的套接字 Sa,以获取新的端口号 Pb 进行数据传输。获取Pb后,关闭Sa并与Pb创建一个新的套接字Sb,但客户端总是说“连接被拒绝”。

以上都是在Saaccept()之后的子进程fork()中,那么问题出在哪里呢?

while (1)
{
struct sockaddr_in client_addr;
socklen_t length = sizeof(client_addr);

int new_server_socket = accept(server_socket,(struct sockaddr*)&client_addr,&length);
if ( new_server_socket < 0)
{
printf("Server Accept Failed!\n");
break;
}

printf("get new connection!\n");

int child_process_pid = fork();
if(child_process_pid == 0 )
{
close(server_socket);
int dataSock;
char buffer[BUFFER_SIZE];
bzero(buffer,BUFFER_SIZE);
length = recv(new_server_socket,buffer,BUFFER_SIZE,0);
if (length < 0)
{
printf("Server Recieve Data Failed!/n");
exit(1);
}

if(strcmp(buffer, "Get New Port\n") == 0)
{
srand((unsigned)time(NULL));
dataSock = (rand() % 10000) + 20000;
//printf("num is %d\n", num);
char sockNum[6];
sprintf(sockNum, "%d", dataSock);
bzero(buffer, BUFFER_SIZE);
strcpy(buffer, "The new port num is ");
strcat(buffer, sockNum);
strcat(buffer, " \n");

struct sockaddr_in data_server_addr;
bzero(&data_server_addr,sizeof(data_server_addr));

data_server_addr.sin_family = AF_INET;
data_server_addr.sin_addr.s_addr = htons(INADDR_ANY);
data_server_addr.sin_port = htons(dataSock);

int data_server_socket = socket(AF_INET,SOCK_STREAM,0);
if( data_server_socket < 0)
{
printf("Create Socket Failed!");
exit(1);
}

if( bind(data_server_socket,(struct sockaddr*)&data_server_addr,sizeof(data_server_addr)))
{
printf("Server Bind Port : %d Failed!", dataSock);
exit(1);
}

if ( listen(data_server_socket, LENGTH_OF_LISTEN_QUEUE) )
{
printf("Server Listen Failed!");
exit(1);
}

send(new_server_socket,buffer,BUFFER_SIZE,0);
close(new_server_socket);

while(1)
{
struct sockaddr_in client_addr;
socklen_t length = sizeof(client_addr);

int new_data_server_socket = accept(data_server_socket,(struct sockaddr*)&client_addr,&length);

if ( new_data_server_socket < 0)
{
printf("Server Data Connection Accept Failed!\n");
break;
}

printf("get new data connection!\n");

最佳答案

在绑定(bind)成功之前,您不应发送新的端口号。而且您根本不需要使用随机数据端口号。只需指定零,执行 bind(),调用 getsockname(),然后查看系统分配的端口号。然后将发送给客户端。

关于当连接到服务器的新端口套接字时,客户端总是被拒绝连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29651858/

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