c#中将IP地址转换成无符号整型数uint的方法与逆变换方法
我们知道 IP地址就是给每个连接在Internet上的主机分配的一个32bit地址。
按照TCP/IP协议规定,IP地址用二进制来表示,每个IP地址长32bit,比特换算成字节,就是4个字节。
而c#中int32的数就是四个字节的,但是符号要占掉一位所以就不够了,但是无符号的 UInt32 就没有这样的问题。
所以理论上讲:UInt32是可以完整保存一个IP地址的。那下面的两个方法就是对IP与UInt32之间的互转换。
-----------------------
谢谢二楼的热心指正。
2015-07-30 update
方法二、使用物理布局结果进行转换
using System; using System.Net; using System.Runtime.InteropServices; namespace NET { internal static class StructIpUtil { [StructLayout(LayoutKind.Explicit)] private struct IPV4 { [FieldOffset(3)] public Byte IP0; [FieldOffset(2)] public Byte IP1; [FieldOffset(1)] public Byte IP2; [FieldOffset(0)] public Byte IP3; [FieldOffset(0)] public UInt32 IP; } internal static UInt32 ip2int(String ip) { Byte[] bytes = IPAddress.Parse(ip).GetAddressBytes(); IPV4 uip = new IPV4() { IP0 = bytes[0], IP1 = bytes[1], IP2 = bytes[2], IP3 = bytes[3] }; return uip.IP; } } }
public static string Int2IP(UInt32 ipCode) {
byte a = (byte)((ipCode & 0xFF000000) >> 0x18);//24
byte b = (byte)((ipCode & 0x00FF0000) >> 0x10);//16
byte c = (byte)((ipCode & 0x0000FF00) >> 0x8);//8
byte d = (byte)(ipCode & 0x000000FF);
string ipStr = String.Format("{0}.{1}.{2}.{3}", a, b, c, d);
return ipStr;
}
public static UInt32 IP2Int(string ipStr) {
string[] ip = ipStr.Split('.');
uint ipCode = 0xFFFFFF00 | byte.Parse(ip[3]);
ipCode = ipCode & 0xFFFF00FF | (uint.Parse(ip[2]) << 0x8);
ipCode = ipCode & 0xFF00FFFF | (uint.Parse(ip[1]) << 0x10);
ipCode = ipCode & 0x00FFFFFF | (uint.Parse(ip[0]) << 0x18);
return ipCode;
}
byte a = (byte)((ipCode & 0xFF000000) >> 0x18);//24
byte b = (byte)((ipCode & 0x00FF0000) >> 0x10);//16
byte c = (byte)((ipCode & 0x0000FF00) >> 0x8);//8
byte d = (byte)(ipCode & 0x000000FF);
string ipStr = String.Format("{0}.{1}.{2}.{3}", a, b, c, d);
return ipStr;
}
public static UInt32 IP2Int(string ipStr) {
string[] ip = ipStr.Split('.');
uint ipCode = 0xFFFFFF00 | byte.Parse(ip[3]);
ipCode = ipCode & 0xFFFF00FF | (uint.Parse(ip[2]) << 0x8);
ipCode = ipCode & 0xFF00FFFF | (uint.Parse(ip[1]) << 0x10);
ipCode = ipCode & 0x00FFFFFF | (uint.Parse(ip[0]) << 0x18);
return ipCode;
}
浙公网安备 33010602011771号