server
#include <stdio.h> #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdlib.h> 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 "); break; } else if (ret == -1) { printf("read failed "); 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 "); 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 "); exit(1); } if(bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) { printf("bind fialed "); exit(1); } if(listen(listenfd,SOMAXCONN)<0) { printf("listen failed "); 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 "); exit(1); } printf("ip=%s, port=%d ",inet_ntoa(peeraddr.sin_addr),ntohs(peeraddr. sin_port)); pid = fork(); if(pid == -1) { printf("fork failed "); 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