c# ip地址与整数相互转换代码

发布时间:2020-11-07编辑:脚本学堂
c#实现IP地址与整数相互转换的一段代码,将Ip地址分割成整型数字,或将数字形式转换成IP地址格式。

功能:
1、将点分割的IP地址转换成长整形;
2、将长整形转换成点分割的ip地址。

代码:
 

复制代码 代码示例:
using System;
using System.Net;
 
class App
{
    static long ToInt(string addr)
    {
        // careful of sign extension: convert to uint first;
        // unsigned NetworkToHostOrder ought to be provided.
        return (long) (uint) IPAddress.NetworkToHostOrder(
             (int) IPAddress.Parse(addr).Address);
    }
 
    static string ToAddr(long address)
    {
        return IPAddress.Parse(address.ToString()).ToString();
        // This also works:
        // return new IPAddress((uint) IPAddress.HostToNetworkOrder(
        //    (int) address)).ToString();
    }
 
    static void Main()
    {
        //假设www.plcxue.com服务器ip地址为:64.233.187.99,换后的结果为1089059683
        Console.WriteLine(ToInt("64.233.187.99"));
        //1089059683转换后的结果为:64.233.187.99
        Console.WriteLine(ToAddr(1089059683));
        
    }
}