客户端:(client1.c)
1 include<unistd.h> 2 #include<stdlib.h> 3 #include<sys/socket.h> 4 #include<arpa/inet.h> 5 #include<string.h> 6 7 #define BUFSIZE 1024 8 #define SERV_IP "127.0.0.1" 9 #define SERV_PORT 6666 10 int main() 11 { 12 int cfd; 13 int n; 14 char buf[BUFSIZE]; 15 struct sockaddr_in serv_addr; 16 //socklen_t serv_addr_len; 17 cfd = socket(AF_INET, SOCK_STREAM, 0); 18 19 memset(&serv_addr, 0, sizeof(serv_addr)); 20 serv_addr.sin_family = AF_INET; 21 serv_addr.sin_port = htons(SERV_PORT); 22 inet_pton(AF_INET, SERV_IP, &serv_addr.sin_addr.s_addr); 23 if(connect(cfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0) 24 { 25 perror("connect"); 26 exit(1); 27 } 28 29 while(1) 30 { 31 fgets(buf, sizeof(buf), stdin); 32 write(cfd, buf, strlen(buf)); 33 n = read(cfd, buf, sizeof(buf)); 34 write(STDOUT_FILENO, buf, n); 35 } 36 37 close(cfd); 38 return 0; 39 }
服务端:(server1.c)
1 #include<stdio.h> 2 #include<unistd.h> 3 #include<sys/socket.h> 4 #include<stdlib.h> 5 #include<arpa/inet.h> 6 #include<ctype.h> 7 #include<string.h> 8 #define SERV_PORT 6666 9 #define BUFSIZE 1024 10 #define SERV_IP "127.0.0.1" 11 12 int main() 13 { 14 int lfd,cfd; 15 int n; 16 char buf[BUFSIZE]; 17 struct sockaddr_in serv_addr,clie_addr; 18 socklen_t clie_addr_len; 19 lfd=socket(AF_INET,SOCK_STREAM,0); 20 21 serv_addr.sin_family = AF_INET; 22 serv_addr.sin_port = htons(SERV_PORT); 23 serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); 24 //memset(&serv_addr, 0, sizeof(serv_addr)); 25 //inet_pton(AF_INET, SERV_IP, &serv_addr.sin_addr.s_addr); 26 27 28 if(bind(lfd,(struct sockaddr *) &serv_addr, sizeof(serv_addr))==-1) 29 { 30 perror("bind"); 31 exit(1); 32 } 33 34 if(listen(lfd,128)==-1) 35 { 36 perror("listen"); 37 exit(1); 38 } 39 40 clie_addr_len = sizeof(clie_addr); 41 cfd = accept(lfd, (struct sockaddr *) & clie_addr, &clie_addr_len); 42 if(cfd<0) 43 { 44 perror("accept"); 45 exit(1); 46 } 47 while(1) 48 { 49 n = read (cfd, buf, sizeof(buf)); 50 for (int i = 0; i < n; i++) 51 buf[i] = toupper(buf[i]); 52 write (cfd, buf, n); 53 54 } 55 close(cfd); 56 close(lfd); 57 return 0; 58 }