之前学习的时候笔记没有保存好,这次重新编写一个案例。
客户端实现程序代码:
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #define DEF_TCP_SRV_PORT 19868 int main() { struct sockaddr_in addr; struct sockaddr_in srv_addr; int net_sock; int new_fd; int res; int len; char buff[128]; // 1. socket 初始化 // 1.1 创建socket net_sock = socket(AF_INET,SOCK_STREAM,0); if( -1 == net_sock ) { printf("create socket error! "); return -1; } // 1.2 初始化地址 bzero( &addr, sizeof(struct sockaddr_in)); addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_family = AF_INET; addr.sin_port = htons(DEF_TCP_SRV_PORT); // 1.3 bind地址 bind( net_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); //监听 listen( net_sock, 5 ); len = sizeof(struct sockaddr); new_fd = accept( net_sock, (struct sockaddr *)(&srv_addr),&len ); printf("server ip:%s ",inet_ntoa(srv_addr.sin_addr)); res = recv(new_fd, buff,125,0); buff[res] ='