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地址";
    }
}

調用演示:ui

Console.WriteLine("192.168.0.1轉數字:{0}\r\n數字轉IP:{1}",IPToID("192.168.0.1"),IDToIP("3232235521"));
相關文章
相關標籤/搜索