server
#include#include /* See NOTES */#include #include #include #include #include #include #include void do_service(int conn){ char recvbuf[1024]; while(1) { memset(recvbuf,0,sizeof(recvbuf)); int ret = read(conn,recvbuf,sizeof(recvbuf)); if(ret == 0) { printf("client close\n"); break; } else if (ret == -1) { printf("read failed \n"); exit(1); } fputs(recvbuf,stdout); write(conn,recvbuf,ret); }}int main(void){ int listenfd; listenfd = socket(PF_INET,SOCK_STREAM,0); if(listenfd < 0) { printf("creat socket failed\n"); exit(1); } struct sockaddr_in servaddr; memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(5188); servaddr.sin_addr.s_addr = htonl(INADDR_ANY);//host any address int n=1; if(setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&n,sizeof(n))<0) { printf("set resueaddr failed\n"); exit(1); } if(bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) { printf("bind fialed\n"); exit(1); } if(listen(listenfd,SOMAXCONN)<0) { printf("listen failed\n"); exit(1); } struct sockaddr_in peeraddr; socklen_t peerlen = sizeof(peeraddr); int conn; pid_t pid; while(1) { if((conn=accept(listenfd,(struct sockaddr*)&peeraddr,&peerlen))<0) { printf("accept failed\n"); exit(1); } printf("ip=%s, port=%d\n",inet_ntoa(peeraddr.sin_addr),ntohs(peeraddr.sin_port)); pid = fork(); if(pid == -1) { printf("fork failed\n"); exit(1); } if (pid == 0) { close(listenfd); do_service(conn); exit(1); } else { close(conn); } } return 0;}
client 参考http://www.cnblogs.com/Malphite/p/7529200.html