IPAddress

时间:2022-03-11 14:23:36
 Console.WriteLine("BitConverter.IsLittleEndian = {0}", BitConverter.IsLittleEndian);
Console.WriteLine();
string format = "ipAddress.Address = {0}, 十六进制 = 0x{1}";
string ip = "192.168.1.224";
Console.WriteLine("字符串:" + ip);
IPAddress ipAddress = IPAddress.Parse(ip); Console.WriteLine(format, ipAddress.Address, ipAddress.Address.ToString("x2"));
Console.WriteLine(ipAddress.ToString());
var array = ipAddress.GetAddressBytes();
int index = -;
foreach (byte b in array)
{
index++;
Console.WriteLine("array[{0}] = 0x{1}", index, b.ToString("x2"));
}
Console.WriteLine(); uint number = ;
Console.WriteLine("无符号整数:" + number + " 0x" + number.ToString("x2"));
ipAddress = IPAddress.Parse(number.ToString());
Console.WriteLine(format, ipAddress.Address, ipAddress.Address.ToString("x2"));
Console.WriteLine(ipAddress.ToString());
array = ipAddress.GetAddressBytes();
index = -;
foreach (byte b in array)
{
index++;
Console.WriteLine("array[{0}] = 0x{1}", index, b.ToString("x2"));
}
Console.WriteLine(); number = ;
Console.WriteLine("无符号整数:" + number + " 0x" + number.ToString("x2"));
ipAddress = IPAddress.Parse(number.ToString());
Console.WriteLine(format, ipAddress.Address, ipAddress.Address.ToString("x2"));
Console.WriteLine(ipAddress.ToString());
array = ipAddress.GetAddressBytes();
index = -;
foreach (byte b in array)
{
index++;
Console.WriteLine("array[{0}] = 0x{1}", index, b.ToString("x2"));
}
Console.WriteLine();

输出结果:

机器字节序为小端

BitConverter.IsLittleEndian = True

字符串:192.168.1.224
ipAddress.Address = 3758205120, 十六进制 = 0xe001a8c0
192.168.1.224
array[0] = 0xc0
array[1] = 0xa8
array[2] = 0x01
array[3] = 0xe0

无符号整数:3232236000 0xc0a801e0
ipAddress.Address = 3758205120, 十六进制 = 0xe001a8c0
192.168.1.224
array[0] = 0xc0
array[1] = 0xa8
array[2] = 0x01
array[3] = 0xe0

无符号整数:3758205120 0xe001a8c0
ipAddress.Address = 3232236000, 十六进制 = 0xc0a801e0
224.1.168.192
array[0] = 0xe0
array[1] = 0x01
array[2] = 0xa8
array[3] = 0xc0

分析:将一个无符号的数字3232236000进行ip地址的解析,3232236000在本机上是按照小端进行排列的。0xc0a801e0

ip地址解析之后,直接按照网络字节序(大端)进行了转换,所以在打印ipAddress.Address会发现数字被反转了。0xe001a8c0

IPAddress.ToString()得到的字符串,和IPAddress.Address是反的

192.168.1.18    对应的Address是0x1201A8C0   高位在低地址存储

  uint number = ;

                IPAddress ipAddress1 = IPAddress.Parse(number.ToString());
Console.WriteLine(ipAddress1.ToString());
Console.WriteLine(ipAddress1.Address);
Console.WriteLine();
IPAddress ipAddress2 = new IPAddress(number);
Console.WriteLine(ipAddress2.ToString());
Console.WriteLine(ipAddress2.Address);

IPAddress