服务端:
/************************************************************************* > File Name: srv.c > Author: zhoulin > Mail: 715169549@163.com > Created Time: Sat 02 Jan 2016 04:39:53 PM EST ************************************************************************/ #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define size 4096 #define port 6000 #define backlog 5 int main(void) { int sk; int rsk; struct sockaddr_in server; struct sockaddr_in client; char send_buf[size]; char recv_buf[size]; //open a socket sk= socket(AF_INET,SOCK_STREAM,0); //建立socket if(sk == -1) { perror("socket"); return -1; } //seting server addr memset((char *)&server,0,sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = port; if(bind(sk, (struct sockaddr *)&server, sizeof(server)) == -1) { //绑定到指定的port上 perror("bind"); return -1; } if(listen(sk, backlog) == -1) { //监听服务端的端口 perror("listen"); return -1; } int len=sizeof(client); printf("****************listen socket**************** "); while(1) { if((rsk = accept(sk,(struct sockaddr *)&client, &len)) < 0){ //循环监听 perror("accept"); return -1; } fprintf(stdout,"Conencted from %s ", inet_ntoa(client.sin_addr)); //输出连接到服务端的IP地址 printf("TCP>"); memset(send_buf,'