server.c
1 # include<stdio.h> 2 # include<arpa/inet.h> 3 # include<stdlib.h> 4 # include<unistd.h> 5 # include<sys/socket.h> 6 # include<sys/mman.h> 7 int main(int argc, const char *argv[]) 8 { 9 int sfd=socket(AF_INET,SOCK_STREAM,0),cfd,n,*count; //count记录登陆的用户数量 10 count=(int *)mmap(NULL,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0); //开辟一个共享内存空间,把地址返回给count 11 *count=0; 12 struct sockaddr_in s,c; 13 char buf[128]; 14 socklen_t len; 15 s.sin_family=AF_INET; //后三行初始化一个socket地址。inet_addr 将字符串强制转化ip地址,htons将整数转化为网络可识别的 16 s.sin_addr.s_addr=inet_addr(argv[1]); 17 s.sin_port=htons(atoi(argv[2])); 18 bind(sfd,(struct sockaddr *)&s,sizeof(s)); //绑定服务器接口 19 listen(sfd,5); //打开监听 20 while(1) 21 { 22 puts("Waitting..............."); 23 len=sizeof(c); 24 cfd=accept(sfd,(struct sockaddr *)&c,&len); //接收来自客户端的连接 25 printf("%s login, now user is %d ",inet_ntoa(c.sin_addr),++(*count)); //inet_ntoa将ip地址转化为字符串 26 while(fork()==0) //开辟多进程 27 { 28 close(sfd); 29 while((n=recv(cfd,buf,sizeof(buf),0))!=0) //接收客户端发来的数据再发回去 30 { 31 buf[n]='