1 #include <stdio.h> 2 #include <unistd.h> 3 #include <sys/socket.h> 4 #include <netinet/in.h> 5 #include <arpa/inet.h> 6 int main(int argc, char const *argv[]) 7 { 8 // 1.创建套接字(TCP) 9 int sockfd = socket(AF_INET, SOCK_STREAM, 0); 10 if (sockfd < 0) 11 { 12 perror("socket"); 13 return -1; 14 } 15 // 2.连接服务器 16 struct sockaddr_in server_addr; 17 server_addr.sin_family = AF_INET; 18 server_addr.sin_port = htons(8000); 19 server_addr.sin_addr.s_addr = inet_addr("10.9.42.228"); 20 int ret = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)); 21 if (ret != 0) 22 { 23 perror("connect"); 24 return -1; 25 } 26 // 3.发送消息 27 send(sockfd, "hi server", sizeof("hi server"), 0); 28 // 4.接受消息 29 char buf[1024] = ""; 30 recv(sockfd, buf, sizeof(buf), 0); 31 printf("recv:%s\n", buf); 32 // 5.关闭套接字 33 close(sockfd); 34 return 0; 35 }
标签:include,addr,int,TCP,server,sockfd,C语言,buf,客户端 From: https://www.cnblogs.com/mengyaoli/p/17899846.html