我的代碼是:收盤插座
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()函數實際釋放套接字,以便它可以立即再次使用它。那麼我在這裏錯過了什麼?
此代碼在發出「Hello,world!」後始終終止服務器。 – alk
在調用套接字上的close()之前調用'shutdown()'不是一個壞主意。 – alk
你還沒有調用fork()來清理子進程,還有一件事你沒有在return 0之前調用'exit(code)',我不確定是否使用'return 0'會讓內核關閉所有你打開的fds,而'exit(code)'做的,如果你不想在返回0之前使用exit(code)'close(sockfd)', if(send(new_fd,「Hello,world!\ n」,MAXDATASIZE,0)== -1)'。 –