linux - C Socket program example - Error on binding: Already in use -
i have following example code using linux sockets:
void serve_request(int newsockfd) { char buffer[256]; int n; /*if connection established start communicating*/ bzero(buffer, 256); n=read(newsockfd, buffer, 255); if(n<0) { perror("error reading socket"); } printf("here message: %s\n",buffer); /*write response client*/ n=write(newsockfd,"i got message", 18); if(n<0) { perror("error writing socket"); exit(1); } //close(newsockfd); } int main(int argc, char* argv) { int sockfd, newsockfd, portno, clilen; char buffer[256]; struct sockaddr_in serv_addr, cli_addr; int n; /*first call socket function*/ sockfd=socket(af_inet, sock_stream, 0); setsockopt(sockfd, sol_socket, so_reuseaddr, 0, 0); if(sockfd<0) { perror("error opening socket"); exit(1); } /*initialize socket structure*/ bzero((char*)&serv_addr, sizeof(serv_addr)); portno=5001; serv_addr.sin_family=af_inet; serv_addr.sin_addr.s_addr=inaddr_any; serv_addr.sin_port=htons(portno); /*now bind host address using bind() call.*/ if(bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr))<0) { perror("error on binding"); exit(1); } /*now start listening clients, here process go in sleep mode , wait incoming connection*/ listen(sockfd, 5); clilen=sizeof(cli_addr); while(1) { /*accept actual connection client*/ newsockfd=accept(sockfd, (struct sockaddr*)&cli_addr, &clilen); if(newsockfd<0) { perror("error on accept"); exit(1); } serve_request(newsockfd); } return 0; }
everything works fine this. when execute ./a.out
starts socket server , waits clients. when exit code using ^c
stops , returns prompt.
however, if code complied last line (//close(newsockfd);
) in method void serve_request(int newsockfd)
uncommented , client had come , gone, on pressing ^c
, invoking server again ./a.out
, shows error on binding: in use
.
but if have compiled code last line commented, works fine, meaning can invoke server ./a.out
, have server again without waiting time in previous case.
can throw light on handling this. appreciated. thank you.
when opened socket, allocated operating system resource , told o/s taht want reuse socket address.
there no automatic cleanup when program ends. resource remains allocated.
uncomment close()
, habit of freeing , resources,whether memory, sockets, mutexes or whatever.
Comments
Post a Comment