gpt4 book ai didi

c - 接受函数不等待连接(不阻塞)

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

我正在尝试用 C 语言制作一个简单的套接字服务器,并按照“The Art Of Exploitation”一书中的教程进行操作

每次我尝试运行服务器时,都会得到输出:

Could not accept new connection

我的C代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define PORT 4444

int main(void) {
// Declare initial values;
int domain, sock_fd, type;
struct sockaddr_in localAddr;
socklen_t addr_length;
...
sock_fd = socket(domain, type, 0);
...
bind(sock_fd, (struct sockaddr *) &localAddr, sizeof(struct sockaddr))
...
// Setup listening
sock_fd = listen(sock_fd, 1);
char buffer[1024];
int sin_size, recv_len;
while (1) {
int client_fd;
struct sockaddr_in clientAddr;
sin_size = sizeof(clientAddr);
client_fd = accept(sock_fd, (struct sockaddr *) (&clientAddr), &sin_size);
if (client_fd == -1) { <----------- HERE
printf("Could not accept new connection");
exit(-1);
}
close(client_fd);
}
close(sock_fd);
return 0;
}

最佳答案

编译器针对您的代码给出了许多错误和警告。

但我猜破坏交易的是你正在做的事情,

 sock_fd = listen(sock_fd, 1);

应该是,

 listen(sock_fd, 1);

并且您正在使用带有未初始化变量的套接字命令。

// sock_fd = socket(domain, type, 0); // wrong
(sock_fd=socket(AF_INET,SOCK_STREAM,0); // correct

以下设置也丢失了,

// The following three lines were missing
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
localAddr.sin_port = htons(PORT);

这是带有更多修复的完整代码,其中仍然有一些有关未使用变量等的警告,但至少它一直“准备好接受连接”。

您确实应该打开编译器上所有可能的警告并阅读 Beej's network programming book .

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define PORT 4444

int main(void) {
// Declare initial values;
int domain, sock_fd, type;
struct sockaddr_in localAddr;

// The following three lines were missing
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
localAddr.sin_port = htons(PORT);

socklen_t addr_length;

// sock_fd = socket(domain, type, 0);
//////////////////////Creating a SOCKET/////////////////////////
if((sock_fd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("ERROR:Socket failed\n");
return -1;
}

if (bind(sock_fd, (struct sockaddr *) &localAddr, sizeof(struct sockaddr)) == -1)
{
printf("ERROR:Binding on server\n");
close(sock_fd);
return -1;
}

// Setup listening
listen(sock_fd, 1);
char buffer[1024];
int sin_size, recv_len;
while (1) {
int client_fd;
struct sockaddr_in clientAddr;
sin_size = sizeof(clientAddr);
client_fd = accept(sock_fd, NULL, NULL);
if (client_fd == -1) {
printf("Could not accept new connection");
exit(-1);
}
close(client_fd);
}
close(sock_fd);
return 0;
}

关于c - 接受函数不等待连接(不阻塞),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55042257/

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