协议不支持的地址族 [英] Address family not supported by protocol
问题描述
以下代码是TCP客户端的套接字编程示例.
Following code is a socket programming sample for a TCP client.
但是当我运行此命令时,connect()返回为协议不支持的地址族.
But when I run this, connect() is returned as Address family not supported by protocol.
我听说,如果平台不支持ipv6,则会出现此问题.
I have heard, this problem will happen if the platform does not support ipv6.
但是我写的AF_INET是ipv4.
But AF_INET I wrote is ipv4.
我的服务器CentOS6.4也在inet6 addr中配置.
Also my server, that is CentOS6.4, is configured within an inet6 addr .
有人知道为什么吗?
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int
main(){
struct sockaddr_in server;
int sock;
char buf[32];
int n;
sock = socket(AF_INET,SOCK_STREAM,0);
perror("socket");
server.sin_family = AF_INET;
server.sin_port = htons(12345);
inet_pton(AF_INET,"127.0.0.1",&server,sizeof(server));
connect(sock,(struct sockaddr *)&server,sizeof(server));
perror("connect");
memset(buf,0,sizeof(buf));
n = read(sock,buf,sizeof(buf));
perror("read");
printf("%d,%s\n",n,buf);
close(sock);
return 0;
}
推荐答案
代码将错误的目标地址和错误数量的参数传递给inet_pton()
. (对于后者,编译器应该警告过您,顺便说一句)
The code passes the wrong destination address and wrong number of arguments to inet_pton()
. (For the latter the compiler should have warned you about, btw)
此行
inet_pton(AF_INET, "127.0.0.1", &server, sizeof(server));
应该是
inet_pton(AF_INET, "127.0.0.1", &server.sin_addr);
逐字记录来自 man inet_pton
:
Verbatim from man inet_pton
:
int inet_pton(int af,const char * src,void * dst);
AF_INET
[...]地址被转换为 一个struct in_addr并复制到dst,该长度必须为sizeof(struct in_addr)(4)字节(32位)长.
[...] The address is converted to a struct in_addr and copied to dst, which must be sizeof(struct in_addr) (4) bytes (32 bits) long.
与问题无关,但也有问题,是read()
返回ssize_t
而不是int
.
Not related to the problem, but also an issue, is that read()
returns ssize_t
not int
.
以下行应调整:
int n;
[...]
printf("%d, %s\n", n, buf);
成为:
ssize_t n;
[...]
printf("%zd, %s\n", n, buf);
这篇关于协议不支持的地址族的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!