我正在尝试使用C语言制作一个简单的套接字服务器,并遵循《剥削的艺术》一书中的教程
每次尝试运行服务器时,都会得到输出:
无法接受新连接
我的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;
}
答案 0 :(得分:0)
编译器会为您的代码提供许多错误和警告。
但是我想最关键的是你在做什么,
sock_fd = listen(sock_fd, 1);
应该是
listen(sock_fd, 1);
并且您正在使用带有未初始化变量的socket命令。
// 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;
}