如何在C中将IP4和IP6地址转换为长值?

如何在C中将IP4和IP6地址转换为长值?,c,sockets,ip,ip-address,C,Sockets,Ip,Ip Address,我需要一个同时使用IP4和IP6地址的函数,并且需要将地址从字符串表示(IP4)或十六进制表示(IP6)转换为长值。我目前的代码是: struct addrinfo *addr; // This converts an char* ip_address to an addrinfo, so now I know whether // it's a IP4 or IP6 address int result = getaddrinfo(ip_address, NULL, NULL, &a

我需要一个同时使用IP4和IP6地址的函数,并且需要将地址从字符串表示(IP4)或十六进制表示(IP6)转换为长值。我目前的代码是:

struct addrinfo *addr;
// This converts an char* ip_address to an addrinfo, so now I know whether 
// it's a IP4 or IP6 address
int result = getaddrinfo(ip_address, NULL, NULL, &addr);
if (result ==0) {
    struct in_addr dst;
    result = inet_pton(addr->ai_family, ip_address, &dst);
    long ip_value = dst->s_addr;
    freeaddrinfo(addr);
    return ip_value;
}

我确实从dst->s_addr得到了一个长消息,但我很确定这是不正确的。任何关于如何解决这一问题的建议都将不胜感激

首先,您的
dst
对于
IPv6
地址来说不够大:

unsigned char buf[sizeof(struct in6_addr)]; /* Since it's larger than in_addr */
int result = getaddrinfo(ip_address, NULL, NULL, buf);
如果地址是IPv4,
buf
是地址中的
,它是一个
uint32\t

uint32_t u;
memcpy(&u, buf, sizeof(u));

如果地址是IPv6,转换为
long
实际上没有意义。你需要的是
128
位宽的东西,或者是你自己的。最后一点并不容易,所以问问自己:你确定你需要这个吗?

嗨,非常感谢你的帮助!当你说我的inet\u pton调用错误时,你是指getaddrinfo调用?关于IP6,是的,它应该是128位,我知道我们需要它,所以我宁愿现在修复它。。。。我是否也需要修复inet\u pton呼叫?@DrDee抱歉,我误解了这个问题。您的
inet\u pton
调用实际上几乎是正确的,我编辑了我的答案。buf中的值始终是140734799738144(我猜这是6\u addr中结构的大小)。抱歉,我一直在问,但我如何从这里得到ip地址的“长”表示形式?@DrDee
in6\u addr
要大得多(
2^128
)。除了手工操作之外,我不知道如何获得128位数字的十进制表示。