IP地址与数字地址相互转换

/// <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}\r\n数字转IP:{1}",IPToID("192.168.0.1"),IDToIP("3232235521"));

 

版权声明:本文为chinalantian原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/chinalantian/p/5275196.html