Linux网络编程——详解SOCKET( 三 )

写一个服务器例子和客户端例子服务器
#include#include#include #include #include#include #include #include #define Port 6666 //端口号#define MAXCLIENT 10 //最大客户端数量int main(int argc, char argv[]){ int socket_fd, client_fd; int ret; int addr_size; struct sockaddr_in server_addr;struct sockaddr_in client_addr;int read_size; char buffer[1024];//创建socket socket_fd = socket(AF_INET, SOCK_STREAM, 0); if( socket_fd == -1) {printf("socket error\n");exit(1); }//绑定bind bzero(//清空数据server_addr.sin_family = AF_INET;//IPv4 server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//将主机IP转换为网络IP server_addr.sin_port = htons(Port);//将主机端口转换为网络Portret = bind(socket_fd, (struct sockaddr *)( if(ret == -1) {printf("bind error\n");exit(1); }//监听 ret = listen(socket_fd, MAXCLIENT); if(ret == -1) {printf("listen error\n");exit(1); }while(1) {//acceptaddr_size = sizeof(struct sockaddr_in);client_fd = accept(socket_fd, (struct sockaddr *)(if(client_fd == -1){printf("accept error\n");exit(1);}//打印客户端IP将网络地址转换成 .字符串printf("Server get connection from %s\n",inet_ntoa(client_addr.sin_addr));if((read_size = read(client_fd, buffer, 1024)) == -1){printf("Read Error\n");exit(1);}buffer[read_size]='\0';printf("Server received %s\n",buffer);close(client_fd);/* 循环下一个 */}close(socket_fd);return 0;}客户端
#include#include#include #include #include#include #include #include #define Port 6666int main(int argc, char argv[]){ int socket_fd; int ret; char buff[1024]; struct sockaddr_in server_addr;char* str_IP = "172.21.252.7";//创建客户端socket socket_fd = socket(AF_INET, SOCK_STREAM, 0); if( socket_fd == -1) {printf("socket error\n");exit(1); }//连接connect bzero(//清空数据server_addr.sin_family = AF_INET;//IPv4 server_addr.sin_addr.s_addr = inet_addr(str_IP);//将主机IP转换为网络IP server_addr.sin_port = htons(Port);//将主机端口转换为网络Port ret = connect(socket_fd, (struct sockaddr*)( if(ret == -1) {printf("connect error\n");exit(1); }while(1) {//连接成功了,发送数据printf("Please input char:\n");fgets(buff, 1024, stdin);write(socket_fd, buff, strlen(buff));}close(socket_fd); return 0;}运行结果如下
Linux网络编程——详解SOCKET文章插图
注意可通过nc指令测试服务器是否有误
Linux网络编程——详解SOCKET文章插图