////// IP地址转换成数字/// /// IP地址///数字,输入无效IP地址返回0 public static uint IPToID(string addr){ IPAddress IP; if(!IPAddress.TryParse(addr,out IP)) return 0; byte[] bInt = IPAddress.Parse(addr).GetAddressBytes(); if (BitConverter.IsLittleEndian) Array.Reverse(bInt); return BitConverter.ToUInt32(bInt,0);}////// 数字转换成IP地址/// /// 数字///IP地址 public static string IDToIP(uint address){ string str=string.Empty; try { return str = IPAddress.Parse(address.ToString()).ToString(); } catch (FormatException) { return str = "不是有效的IP地址"; }}
调用演示:
Console.WriteLine("192.168.0.1转数字:{0}\r\n数字转IP:{1}",IPToID("192.168.0.1"),IDToIP("3232235521"));