文章目录
- 4.15 TCP通信实现(服务器端)
- 4.16 TCP通信实现(客户端)
4.15 TCP通信实现(服务器端)
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>int main(){int lfd = socket(AF_INET,SOCK_STREAM,0);if(lfd == -1){perror("socket");exit(0);}struct sockaddr_in saddr;saddr.sin_family = AF_INET; inet_pton(AF_INET,"192.168.65.129",&saddr.sin_addr.s_addr); saddr.sin_port = htons(9999);int ret = bind(lfd,(struct sockaddr*)&saddr,sizeof(saddr));if(ret == -1){perror("bind");exit(0);}ret = listen(lfd,8);if(ret == -1){perror("listen");exit(0);}struct sockaddr_in clientaddr;socklen_t len = sizeof(clientaddr);int cfd = accept(lfd,(struct sockaddr*)&clientaddr,&len);if(cfd == -1){perror("accept");exit(0);}char clientIp[16];inet_ntop(AF_INET,&clientaddr.sin_addr.s_addr,clientIp,sizeof(clientIp));unsigned short clientPort = ntohs(clientaddr.sin_port);printf("client IP is: %s, port is %d: \n",clientIp,clientPort);char recvBuf[1024] = {0};len = read(cfd,recvBuf,sizeof(recvBuf));if(len == -1){perror("accept");exit(0);}else if(len > 0){printf("recv client data = %s\n",recvBuf);}else if(len == 0){printf("client close...");}char* data = "hello,i am server";write(cfd,data,strlen(data));close(cfd);close(lfd);return 0;
}
4.16 TCP通信实现(客户端)
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>int main(){int lfd = socket(AF_INET,SOCK_STREAM,0);if(lfd == -1){perror("socket");exit(0);}struct sockaddr_in saddr;saddr.sin_family = AF_INET; inet_pton(AF_INET,"192.168.65.129",&saddr.sin_addr.s_addr); saddr.sin_port = htons(9999);int ret = bind(lfd,(struct sockaddr*)&saddr,sizeof(saddr));if(ret == -1){perror("bind");exit(0);}ret = listen(lfd,8);if(ret == -1){perror("listen");exit(0);}struct sockaddr_in clientaddr;socklen_t len = sizeof(clientaddr);int cfd = accept(lfd,(struct sockaddr*)&clientaddr,&len);if(cfd == -1){perror("accept");exit(0);}char clientIp[16];inet_ntop(AF_INET,&clientaddr.sin_addr.s_addr,clientIp,sizeof(clientIp));unsigned short clientPort = ntohs(clientaddr.sin_port);printf("client IP is: %s, port is %d: \n",clientIp,clientPort);char recvBuf[1024] = {0};len = read(cfd,recvBuf,sizeof(recvBuf));if(len == -1){perror("accept");exit(0);}else if(len > 0){printf("recv client data = %s\n",recvBuf);}else if(len == 0){printf("client close...");}char* data = "hello,i am server";write(cfd,data,strlen(data));close(cfd);close(lfd);return 0;
}