客戶端:#include <stdio.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> int main(int argc,char *argv[]) {int sockfd,numbytes;char buf[100];struct sockaddr_in their_addr;//int i = 0;//將基本名字和地址轉換//he = gethostbyname(argv[1]);//建立一個TCP套接口if((sockfd = socket(AF_INET,SOCK_STREAM,0))==-1){ perror("socket");printf("create socket error.建立一個TCP套接口失敗");exit(1);} //初始化結構體,連接到服務器的2323端口their_addr.sin_family = AF_INET;their_addr.sin_port = htons(2323);// their_addr.sin_addr = *((struct in_addr *)he->h_addr);inet_aton( "127.0.0.1", &their_addr.sin_addr );bzero(&(their_addr.sin_zero),8);//和服務器建立連接if(connect(sockfd,(struct sockaddr *)&their_addr,sizeof(struct sockaddr))==-1){ perror("connect");exit(1);} //向服務器發送數據if(send(sockfd,"hello!socket.",6,0)==-1){perror("send");exit(1);}//接受從服務器返回的信息if((numbytes = recv(sockfd,buf,100,0))==-1){perror("recv");exit(1);}buf[numbytes] = '\0';printf("Recive from server:%s\n",buf);//關閉socket close(sockfd);return 0; }
服務器端:#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/wait.h> #include <errno.h>int main() {int sockfd,new_fd;struct sockaddr_in my_addr;struct sockaddr_in their_addr;int sin_size;//建立TCP套接口if((sockfd = socket(AF_INET,SOCK_STREAM,0))==-1){ printf("create socket error");perror("socket");exit(1);} //初始化結構體,并綁定2323端口my_addr.sin_family = AF_INET;my_addr.sin_port = htons(2323);my_addr.sin_addr.s_addr = INADDR_ANY;bzero(&(my_addr.sin_zero),8);//綁定套接口if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1){ perror("bind socket error");exit(1);} //創建監聽套接口if(listen(sockfd,10)==-1){perror("listen");exit(1);}//等待連接while(1){sin_size = sizeof(struct sockaddr_in);printf("server is run.\n");//如果建立連接,將產生一個全新的套接字if((new_fd = accept(sockfd,(struct sockaddr *)&their_addr,&sin_size))==-1){perror("accept");exit(1);}printf("accept success.\n");//生成一個子進程來完成和客戶端的會話,父進程繼續監聽if(!fork()){printf("create new thred success.\n");//讀取客戶端發來的信息int numbytes;char buff[256];memset(buff,0,256);if((numbytes = recv(new_fd,buff,sizeof(buff),0))==-1){perror("recv");exit(1);}printf("%s",buff);//將從客戶端接收到的信息再發回客戶端if(send(new_fd,buff,strlen(buff),0)==-1)perror("send");close(new_fd);exit(0);}close(new_fd);}close(sockfd); }