如何在C#中将IPv4地址转换为整数?

如何在C#中将IPv4地址转换为整数?

我正在寻找一个将标准IPv4地址转换为整数的函数。可用于相反功能的奖励积分。

解决方案应该在C#中。


蝴蝶不菲
浏览 565回答 3
3回答

呼如林

实际上,我不认为乘法是最明确的方式(完全正确)。Int32“格式化”的IP地址可以看作以下结构[StructLayout(LayoutKind.Sequential, Pack = 1)]&nbsp;struct IPv4Address{&nbsp; &nbsp;public Byte A;&nbsp; &nbsp;public Byte B;&nbsp; &nbsp;public Byte C;&nbsp; &nbsp;public Byte D;}&nbsp;// to actually cast it from or to an int32 I think you&nbsp;// need to reverse the fields due to little endian所以要转换IP地址64.233.187.99你可以这样做:(64&nbsp; = 0x40) << 24 == 0x40000000(233 = 0xE9) << 16 == 0x00E90000(187 = 0xBB) << 8&nbsp; == 0x0000BB00(99&nbsp; = 0x63)&nbsp; &nbsp; &nbsp; &nbsp;== 0x00000063&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ---------- =|&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 0x40E9BB63所以你可以使用+添加它们,或者你可以将它们组合在一起。结果是0x40E9BB63,这是1089059683.(在我看来,以十六进制看,它更容易看到字节)所以你可以把函数写成:int ipToInt(int first, int second,&nbsp;&nbsp; &nbsp; int third, int fourth){&nbsp; &nbsp; return (first << 24) | (second << 16) | (third << 8) | (fourth);}
打开App,查看更多内容
随时随地看视频慕课网APP