At that time, only one process can bind to a given port, therefore, given the port, we can listen to no more than one process. Yes, several processes can send and receive through the same port, but only one process is bound to a port.
eg. in the following code appears "server: bind: Address An error is already being used . Then, if we run lsof -i: 2100, we will only get one process identifier listening on port 2100.
#define SERVERPORT "2100" #define BUF_MAX 1024 #define BACKLOG 10 int data_connection(char* portno) { struct addrinfo hints,*res,*clientinfo; int rv,datafd,yes=1,new_fd; char buf[BUF_MAX]; struct sockaddr_storage their_addr; socklen_t addr_size; memset(&hints,0,sizeof(hints)); hints.ai_family=AF_UNSPEC; hints.ai_socktype=SOCK_STREAM;//connnection oriented. hints.ai_flags=AI_PASSIVE; if ((rv = getaddrinfo(NULL, portno, &hints, &res)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } for(clientinfo=res;clientinfo!=NULL;clientinfo=clientinfo->ai_next) { if((datafd=socket(clientinfo->ai_family,clientinfo->ai_socktype,clientinfo->ai_protocol))==-1) { perror("server:datasocket"); continue; } break; } if(setsockopt(datafd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int))==-1) { perror("setsockopt"); exit(1); } if(bind(datafd,clientinfo->ai_addr,clientinfo->ai_addrlen)<0) { perror("server:bind"); exit(1); } if(listen(datafd,BACKLOG)<0) { perror("server:listen"); exit(1); } addr_size=sizeof(their_addr); if((new_fd=accept(datafd,(struct sockaddr*)&their_addr,&addr_size))<0) { perror("server:accept"); exit(1); } close(datafd); datafd=new_fd; return datafd; } int main() { int datafd; fork(); datafd=data_connection(SERVERPORT); }
source share