标签:sys color sock 网络 size add style rom eof
服务器:
/* *tcp_server.c */ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #define SER_PORT 8000 #define MAX_LINE 1024 int main(int argc, char **argv) { int listenfd, connfd; struct sockaddr_in servaddr, cliaddr; socklen_t cliaddr_len; char buff[MAX_LINE]; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SER_PORT); bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); listen(listenfd, 20); while(1) { cliaddr_len = sizeof(cliaddr); connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddr_len); printf("receive from %s at port %d\n", inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)), ntohs(cliaddr.sin_port)); close(connfd); } return 0; }
客户端:
/* *tcp_client.c */ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <string.h> #define SER_PORT 8000 #define MAX_LINE 1024 int main(int argc, char **argv) { int sockfd; struct sockaddr_in servaddr; sockfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr); servaddr.sin_port = htons(SER_PORT); if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { printf("connect error:%s\n", strerror(errno)); } return 0; }
参考:
《UNIX网络编程 - 卷1:套接字联网API》
标签:sys color sock 网络 size add style rom eof
原文地址:https://www.cnblogs.com/hustluotao/p/10182711.html