简体   繁体   English

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

[英]How to convert IP4 and IP6 addresses to long value in C?

I need a function that works both with IP4 and IP6 addresses and I need to convert an address from it's string representation (IP4) or hexdecimal representation (IP6) to it's long value. 我需要一个可同时用于IP4和IP6地址的函数,并且需要将地址从其字符串表示形式(IP4)或十六进制表示形式(IP6)转换为其长值。 The current code I have is: 我当前的代码是:

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;
}

I do get a long from dst->s_addr but I am pretty sure that this is incorrect. 我确实从dst-> s_addr中获取了很长时间,但是我很确定这是不正确的。 Any pointers on how to solve this are much appreciated! 任何有关如何解决此问题的指针,我们将不胜感激!

First of all your dst isn't large enough for an IPv6 address: 首先,您的dst不足以容纳IPv6地址:

unsigned char buf[sizeof(struct in6_addr)]; /* Since it's larger than in_addr */
int result = getaddrinfo(ip_address, NULL, NULL, buf);

If the address is IPv4, buf is an in_addr which is an uint32_t . 如果地址是IPv4,则bufin_addr ,它是uint32_t

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

If the address is IPv6 converting to long doesn't actually make sense. 如果地址是IPv6,则转换为long实际上没有任何意义。 You need something that's 128 bits wide or roll your own. 您需要128位宽的东西或自己动手。 That last bit isn't so easy, so ask yourself: are you sure you need this ? 最后一点不是那么容易,所以问问自己:您确定需要这个吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM