Handling of BIND errors:
Bind:address already in use
Cause: The operating system does not immediately release the port
Resolution one: Wait for a period of time to run the network program
Resolution two: Set by setsockopt, the key code is as follows.
1 //resolves an issue in which a wait_time after close causes bind to fail2 intval =1;3 intret = setsockopt (SFD,SOL_SOCKET,SO_REUSEADDR, (void*) &val,sizeof(int));4 if(ret = =-1)5 {6printf"setsockopt");7Exit1);8}
Example: Taking a multi-process concurrent server as an example
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4 5#include <sys/types.h>6#include <sys/socket.h>7#include <netinet/inch.h>8#include <arpa/inet.h>9#include <signal.h>Ten One #definePORT 7788 A - intinit_tcp () - { the //1. Create Sockets-Set Protocol - intSFD = socket (Af_inet,sock_stream,0); - if( -1==SFD) - { +Perror ("Socket"); -Exit (-1); + } A //2. Resolve an issue with wait_time after close that causes bind to fail at intval =1; - intret = setsockopt (SFD,SOL_SOCKET,SO_REUSEADDR, (void*) &val,sizeof(int)); - if(ret = =-1) - { -printf"setsockopt"); -Exit1); in } - //3. Bind IP and Port to structsockaddr_in saddr; +saddr.sin_family =af_inet; -SADDR.SIN_ADDR.S_ADDR =Inaddr_any; theSaddr.sin_port =htons (PORT); *ret = bind (SFD, (structSOCKADDR *) &saddr,sizeof(SADDR)); $ if(ret = =-1)Panax Notoginseng { -printf"Bind"); theExit1); + } A //4. Monitoring theRET = Listen (SFD,5); + if(ret = =-1) - { $printf"Listen"); $Exit1); - } -printf"Server is ready ... \ n"); the - returnsfd;Wuyi } the - voidDeal_communication (intCfD) Wu { - Charbuf[ -] = {' /'}; About while(1) $ { -memset (BUF,' /',sizeof(BUF)); -Recv (Cfd,buf,sizeof(BUF),0); -printf"Client say:%s\n", buf); ASend (Cfd,buf,strlen (BUF),0); + if(STRNCMP (BUF,"quit",4) ==0) the Break; - } $ the return ; the } the the - intMain () in { the //1. Initialize (create socket socket/address multiplexing +bind/listen) the intSFD =init_tcp (); About //2. Concurrent processing client (accept/fork) 2-2 communication the while(1) the { the intCFD =Accept (sfd,null,null); + if(cfd = =-1) - { thePerror ("Accept");BayiExit1); the } the - //fork-create a child process - if(fork () = =0) the { the deal_communication (CFD); the Close (CFD); theExit0); - } the Close (CFD); the signal (SIGCHLD,SIG_DFL); the }94 Close (SFD); the return 0; the}
Resolve bind error bind:address already in use