gpt4 book ai didi

关闭 BSD 套接字中的套接字

转载 作者:太空宇宙 更新时间:2023-11-04 00:39:59 28 4
gpt4 key购买 nike

我的代码是:

int main(int argc, char *argv[])
{
int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd */
struct sockaddr_in my_addr; /* my address information */
struct sockaddr_in their_addr; /* connector's address information */
socklen_t sin_size;

/* generate the socket */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}

/* generate the end point */
my_addr.sin_family = AF_INET; /* host byte order */
my_addr.sin_port = htons(MYPORT); /* short, network byte order */
my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */
/* bzero(&(my_addr.sin_zero), 8); ZJL*/ /* zero the rest of the struct */

/* bind the socket to the end point */
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) \
== -1) {
perror("bind");
exit(1);
}

/* start listnening */
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}

printf("server starts listnening %d...\n",sockfd);

/* repeat: accept, send, close the connection */
/* for every accepted connection, use a sepetate process or thread to serve it */
while(1) { /* main accept() loop */
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, \
&sin_size)) == -1) {
perror("accept");
continue;
}
printf("server: got connection from %s\n", \
inet_ntoa(their_addr.sin_addr));

if ((numbytes=recv(new_fd, buf, MAXDATASIZE, 0)) == -1) {
perror("recv");
exit(1);
}

buf[numbytes] = '\0';

printf("Received: %s",buf);

if (send(new_fd, "Hello, world!\n", MAXDATASIZE, 0) == -1)
perror("send");
close(new_fd);
exit(0);

close(new_fd); /* parent doesn't need this */

while(waitpid(-1,NULL,WNOHANG) > 0); /* clean up child processes */
}
return 0;
}

因此,每当我执行此服务器时,在一个客户端使用它后它就会终止。但是如果我想在 60 秒内再次执行它,那么它会给出一个错误 bind: Address already in use 我认为 close() 函数实际上释放了套接字以便它可用立即再次使用它。那么我在这里缺少什么?

最佳答案

在调用 bind 之前,您可以使用 SO_REUSEADDR 套接字选项标记您想要潜在地重用一个地址/端口:

int reuseaddr = 1;
int err = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
&reuseaddr, sizeof(reuseaddr));

关于关闭 BSD 套接字中的套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13041335/

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