/// <summary> /// IP地址转换成数字 /// </summary> /// <param name="addr">IP地址</param> /// <returns>数字,输入无效IP地址返回0</returns> 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); } /// <summary> /// 数字转换成IP地址 /// </summary> /// <param name="address">数字</param> /// <returns>IP地址</returns> 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} 数字转IP:{1}",IPToID("192.168.0.1"),IDToIP("3232235521"));