正在将IP地址字节转换为整数

Converting IP Address bytes to integer

本文关键字:转换 整数 字节 地址 IP      更新时间:2023-10-16

例如:

1.要转换32位IP地址(IPv4):

unsigned char ByteAddress[4];
unsigned int* IntegerAddress;
IntegerAddress = reinterpret_cast<unsigned int*> &ByteAddress ;

然后我可以使用IntegerAddress来比较ip地址。

2.要转换128位IP地址(IPv6):

unsigned char ByteAddress[16];
uint64_t* LongAddress;
LongAddress = reinterpret_cast<uint64_t*> &ByteAddress

然后我可以使用LongAddress[0]和LongAddress[1]来比较ip地址。

它是否比使用移位运算符更可取(因为它更快)?这是良好的编程实践吗?它适用于所有平台(尤其是unix和windows64)和编译器(C++、VS2010)

我认为,你可以为使用联合

union Int32And4Bytes {
int32_t IntegerValue;
unsigned char ByteArray[4];
};

它应该正确对齐,IIRC。