1 //服务器端 server.c 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<string.h> 5 #include<errno.h> 6 #include<sys/types.h> 7 #include<sys/socket.h> 8 #include<netinet/in.h> 9 #define MAXLINE 4096 10 11 //socket(int domain, int type, int protocol) 12 // 协议域 socket类型 指定协议 13 int main(int argc, char **argv) 14 { 15 int n, listenfd, connfd; 16 struct sockaddr_in servaddr; 17 char buff[MAXLINE]; 18 if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ) 19 { 20 printf("create socket error:%s(error:%d)\n",strerror(errno),errno); 21 exit(0); 22 } 23 memset(&servaddr, 0, sizeof(servaddr)); 24 servaddr.sin_family = AF_INET; 25 servaddr.sin_addr.s_addr = htonl(INADDR_ANY); //系统绑定默认的网卡即IP地址 26 servaddr.sin_port = htons(6666); //监听本机的6666号端口 27 28 if( bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1) 29 { //把一个地址族中的特定地址赋给socket 30 printf("bind socket error: %s(errno: %d)\n",strerror(errno),errno); 31 exit(0); 32 } 33 if( listen(listenfd, 10) == -1) 34 { //调用listen()监听socket 35 printf("listen socket error: %s(errno: %d)\n",strerror(errno),errno); 36 exit(0); 37 } 38 printf("waiting for client‘s request...\n"); 39 while(1) 40 { 41 if( (connfd = accept(listenfd, (struct sockaddr*)NULL, NULL)) == -1) 42 { //调用accept()函数取接收请求,连接建立好 43 printf("accept socket error: %s(errno: %d)",strerror(errno),errno); 44 continue; 45 } 46 n = recv(connfd, buff, MAXLINE, 0); //recv函数返回其实际copy的字节数 47 buff[n] = ‘\0‘; 48 printf("recv msg from client: %s\n", buff); 49 close(connfd); 50 } 51 close(listenfd); 52 }
1 //客户端 client.c 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<string.h> 5 #include<errno.h> 6 #include<sys/types.h> 7 #include<sys/socket.h> 8 #include<netinet/in.h> 9 #define MAXLINE 4096 10 11 int main(int argc, char** argv) 12 { 13 int n, sockfd; 14 char recvline[MAXLINE], sendline[MAXLINE]; 15 struct sockaddr_in servaddr; 16 if( argc != 2) 17 { 18 printf("usage: ./client <ipaddress>\n"); 19 exit(0); 20 } 21 if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) 22 { 23 printf("create socket error: %s(errno: %d)\n", strerror(errno),errno); 24 exit(0); 25 } 26 memset(&servaddr, 0, sizeof(servaddr)); 27 servaddr.sin_family = AF_INET; 28 servaddr.sin_port = htons(6666); 29 30 if( inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) 31 { //IP地址转换函数 32 printf("inet_pton error for %s\n",argv[1]); 33 exit(0); 34 } 35 if( connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) 36 { //调用connect()发出连接请求 37 printf("connect error: %s(errno: %d)\n",strerror(errno),errno); 38 exit(0); 39 } 40 printf("send msg to server: \n"); 41 fgets(sendline, 4096, stdin); 42 if( send(sockfd, sendline, strlen(sendline), 0) < 0) 43 { 44 printf("send msg error: %s(errno: %d)\n", strerror(errno), errno); 45 exit(0); 46 } 47 close(sockfd); 48 exit(0); 49 }
分别用gcc编译好后执行,开2个终端:
时间: 2024-09-30 20:50:42