linux socket连接中 ERRNO错误
Connection refused:应该是连接的服务端没有启动或者连接端口错误,可以用如下代码测试
client端:
1 #include <stdio.h> 2 #include <sys/types.h> /* See NOTES */ 3 #include <sys/socket.h> 4 #include <strings.h> 5 #include <unistd.h> 6 #include <netinet/in.h> 7 #include <string.h> 8 #include <arpa/inet.h> 9 #include <errno.h> 10 #define PORT 1234 11 #define SERVER "10.1.70.21" 12 13 int main() 14 { 15 int fd = socket(AF_INET, SOCK_STREAM, 0); 16 int nfd; 17 int ret; 18 struct sockaddr_in server_addr, client_addr; 19 bzero(&server_addr, sizeof(server_addr)); 20 21 server_addr.sin_family =AF_INET; 22 server_addr.sin_port = htons(PORT); 23 inet_pton(AF_INET, SERVER, &server_addr.sin_addr); 24 //bind(fd, (struct sockaddr *)&server_addr, sizeof(server_addr)); 25 errno = 0; 26 ret = connect(fd, (struct sockaddr*)&server_addr, sizeof(server_addr)); 27 if(ret == -1) 28 { 29 perror("connect: "); 30 } 31 char buf[1024]; 32 while(1) 33 { 34 bzero(buf, 1024); 35 ret = read(STDIN_FILENO, buf, sizeof(buf)); 36 printf("ret: %d, buf: %s", ret, buf); 37 ret = write(fd, buf, ret); 38 printf("ret:%d\n", ret); 39 if(ret < 0) 40 { 41 perror("write error"); 42 } 43 ret = read(fd, buf, 1024); 44 if(ret < 0) 45 { 46 perror("ret"); 47 } 48 write(STDOUT_FILENO, buf, ret); 49 } 50 return 0; 51 }
server端:
1 #include <stdio.h> 2 #include <sys/types.h> /* See NOTES */ 3 #include <sys/socket.h> 4 #include <strings.h> 5 #include <unistd.h> 6 #include <netinet/in.h> 7 #include <string.h> 8 #include <errno.h> 9 //server端监听端口 10 #define PORT 3388 11 int main() 12 { 13 int fd = socket(AF_INET, SOCK_STREAM, 0);//创建一个socket 14 int nfd; 15 struct sockaddr_in server_addr, client_addr; 16 bzero(&server_addr, sizeof(server_addr)); 17 server_addr.sin_family =AF_INET; //ipv4 18 server_addr.sin_port = htons(PORT);//端口 19 server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//监听本主机的所有ip 20 21 bind(fd, (struct sockaddr *)&server_addr, sizeof(server_addr));//绑定 22 listen(fd, 30);//监听socket连接,30为三次握手队列大小 23 char buf[1024]; 24 // 把server_addr.sin_addr的地址转换成字符串(点分十进制表示) 25 inet_ntop(AF_INET, &server_addr.sin_addr, buf, sizeof(buf)); 26 printf("%s\n", buf);//一般输出为0.0.0.0 27 pid_t pid; 28 while(1) 29 { 30 bzero(buf, sizeof(buf));//buf清零,相当于memset(buf, 0, sizeof(buf)); 31 32 socklen_t len= sizeof(client_addr); 33 nfd = accept(fd, (struct sockaddr*)&client_addr, &len);//接收socket连接 34 inet_ntop(AF_INET, &client_addr.sin_addr, buf, sizeof(buf));//获取socket连接客户端的ip 35 printf("accept connetc %s port %d\n", buf, ntohs(client_addr.sin_port)); 36 37 pid = fork(); 38 //子进程 39 if(pid == 0) 40 { 41 while(1) 42 { 43 44 int ret = read(nfd, buf, sizeof(buf)); 45 if(ret <= 0) 46 { 47 perror("ret"); 48 return 0; 49 } 50 write(STDOUT_FILENO, buf, ret); 51 write(nfd, buf, ret); 52 } 53 } 54 } 55 return 0; 56 }