ConvertIPAddressToNumber
项目中有IP与Int32类型相互转换的需求,于是在网上搜索了相关代码,但发现网上的代码有Bug,加以修改发布如下:
/// <summary> /// 将IPv4格式的字符串转换为int型表示 /// </summary> /// <param name="strIPAddress">IPv4格式的字符</param> /// <returns></returns> public static int IPToNumber(string strIPAddress) { //将目标IP地址字符串strIPAddress转换为数字 string[] arrayIP = strIPAddress.Split('.'); int sip1 = Int32.Parse(arrayIP[0]); int sip2 = Int32.Parse(arrayIP[1]); int sip3 = Int32.Parse(arrayIP[2]); int sip4 = Int32.Parse(arrayIP[3]); int tmpIpNumber; tmpIpNumber = sip1 * 256 * 256 * 256 + sip2 * 256 * 256 + sip3 * 256 + sip4; return tmpIpNumber; } /// <summary> /// 将int型表示的IP还原成正常IPv4格式。 /// </summary> /// <param name="intIPAddress">int型表示的IP</param> /// <returns></returns> public static string NumberToIP(int intIPAddress) { int tempIPAddress; //将目标整形数字intIPAddress转换为IP地址字符串
//-1062731518 192.168.1.2 //-1062731517 192.168.1.3 if (intIPAddress >= 0) { tempIPAddress = intIPAddress; } else { tempIPAddress = intIPAddress + 1; } int s1 = tempIPAddress / 256 / 256 / 256; int s21 = s1 * 256 * 256 * 256; int s2 = (tempIPAddress - s21) / 256 / 256; int s31 = s2 * 256 * 256 + s21; int s3 = (tempIPAddress - s31) / 256; int s4 = tempIPAddress - s3 * 256 - s31; if (intIPAddress < 0) { s1 = 255 + s1; s2 = 255 + s2; s3 = 255 + s3; s4 = 255 + s4; } string strIPAddress = s1.ToString() + "." + s2.ToString() + "." + s3.ToString() + "." + s4.ToString(); return strIPAddress; }
主要修改了 ConvertNumberToIPAddress 方法。原来的代码是什么样子各位在网上搜来看看就知道,运行时的Bug举例:
原始IP | 转化后的数字 | 通过数字还原出来的IP |
0.0.0.0 | 0 | 0.0.0.1 |
255.0.0.0 | -16777216 | 0.-255.-255.-255 |
255.255.0.0 | -65536 | 0.0.-255.-255 |
118.119.250.24 | 1987574296 | 118.119.250.25 |
0.0.0.255 | 255 | 0.0.1.0 |
…… |
上面仅是IP与Int32之间的互转,至于与uint之间的互转网上也有代码,未进行深入测试。