c# IP从192.168.1.1转成int类型

找了一些资料,总结如下:

方法1  .net提供的方法转换IP地址

//字符串转换为数字

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("192.168.1.1");

long dreamduip = ipaddress.Address;

//数字转换为字符串

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse(dreamduip.ToString());

string strdreamduip = ipaddress.ToString();

 

方法2:通过转换方法

//将0xc0a80101转成192.168.1.1

public static string Int2IP(UInt32 ipCode)

{
            byte a = (byte)((ipCode & 0xFF000000>> 0x18);
            byte b = (byte)((ipCode & 0x00FF0000>> 0xF);
            byte c = (byte)((ipCode & 0x0000FF00>> 0x8);
            byte d = (byte)(ipCode & 0x000000FF);
            string ipStr = String.Format("{0}.{1}.{2}.{3}", a, b, c, d);
            return ipStr;
 }
//将192.168.1.1转成0xc0a80101

public static UInt32 IP2Int(string ipStr)

{
            string[] ip = ipStr.Split('.');
            uint ipCode = 0xFFFFFF00 | byte.Parse(ip[3]);
            ipCode = ipCode & 0xFFFF00FF | (uint.Parse(ip[2]) << 0x8);
            ipCode = ipCode & 0xFF00FFFF | (uint.Parse(ip[1]) << 0xF);
            ipCode = ipCode & 0x00FFFFFF | (uint.Parse(ip[0]) << 0x18);
            return ipCode;
 }

posted @ 2015-09-06 14:32  32ID  阅读(614)  评论(0编辑  收藏  举报