UNIX下TCP/IP通信测试程序

来源:互联网 发布:数据库信息管理办法 编辑:程序博客网 时间:2024/05/16 01:51

server:

#include <stdio.h>#include <stdlib.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <string.h>//serverint main(){//1.创建socketint sockfd=socket(PF_INET,SOCK_STREAM,0);if(sockfd==-1)perror(""),exit(-1);//2.准备地址struct sockaddr_in addr;addr.sin_family = PF_INET;addr.sin_port = htons(12345);inet_aton("192.168.182.53",&addr.sin_addr);//3.绑定int res = bind(sockfd,(struct sockaddr*)&addr, sizeof(addr));if(res==-1)perror("绑定失败"),exit(-1);printf("绑定成功\n");//4.监听if(listen(sockfd, 100)==-1)perror("监听失败"),exit(-1);printf("监听启动\n");//5.等待客户端连接struct sockaddr_in fromaddr;//len必需赋值socklen_t len = sizeof(fromaddr);int fd = accept(sockfd, (struct sockaddr*)&fromaddr, &len);if(fd==-1)perror("accept失败");else printf("有客户端连接到服务器\n");//6.通信char buf[100] = {};read(fd, buf, sizeof(buf));printf("客户端%s说:%s\n",inet_ntoa(fromaddr.sin_addr), buf);char* msg = "Welcome my home.";write(fd, msg, strlen(msg)); //7.关闭close(fd);close(sockfd);}

client:

#include <stdio.h>#include <stdlib.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <string.h>//clientint main(){//1.创建socketint sockfd=socket(PF_INET,SOCK_STREAM,0);if(sockfd==-1)perror(""),exit(-1);//2.准备地址struct sockaddr_in addr;addr.sin_family = PF_INET;addr.sin_port = htons(12345);inet_aton("192.168.182.53",&addr.sin_addr);//3.连接int res = connect(sockfd,(struct sockaddr*)&addr, sizeof(addr));if(res==-1)perror("连接失败"),exit(-1);printf("连接成功\n");//4.通信write(sockfd, "您好啊服务器", 12);char buf[100] = {};read(sockfd, buf, sizeof(buf));printf("服务器说:%s\n", buf);//7.关闭close(sockfd);}




原创粉丝点击