A有以下侦听器套接字:
int sd = socket(PF_INET,SOCK_STREAM,0); struct sockaddr_in addr; bzero(&addr,sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(http_port); addr.sin_addr.s_addr = INADDR_ANY; if(bind(sd,(sockaddr*)&addr,sizeof(addr))!=0) { ... } if (listen(sd,16)!=0) { ... } int sent = 0; for(;;) { int client = accept(sd,(socklen_t*)&size); if (client > 0) { ... close(client); } }
如果使用
close(sd);
解决方法
在内核的某个地方,仍然有一些关于您以前的套接字的信息.告诉内核您是否愿意重新使用端口:
int yes=1; //char yes='1'; // use this under Solaris if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes)) == -1) { perror("setsockopt"); exit(1); }
更详细的说明见the bind() section in beej’s Guide to Network Programming.