1 public class CTrans
2 {
3 /// <summary>
4 /// IP地址转数据
5 /// </summary>
6 /// <param name="strIp"> IP地址 </param>
7 /// <returns> 数据 </returns>
8 public static uint IPToData(String strIp)
9 {
10 // 将127.0.0.1 形式的IP地址转换成10进制整数
11 uint [] ip = new uint [ 4 ];
12
13 // 找到IP地址字符串中.的位置
14 int position1 = strIp.IndexOf( " . " );
15 int position2 = strIp.IndexOf( " . " , position1 + 1 );
16 int position3 = strIp.IndexOf( " . " , position2 + 1 );
17
18 // 将每个.之间的字符串转换成整型
19 ip[ 0 ] = Convert.ToUInt32(strIp.Substring( 0 , position1));
20 ip[ 1 ] = Convert.ToUInt32(strIp.Substring(position1 + 1 , position2 - (position1 + 1 )));
21 ip[ 2 ] = Convert.ToUInt32(strIp.Substring(position2 + 1 , position3 - (position2 + 1 )));
22 ip[ 3 ] = Convert.ToUInt32(strIp.Substring(position3 + 1 ));
23
24 // ip0*256*256*256 + ip1*256*256 + ip2*256 + ip3
25 return (ip[ 0 ] << 24 ) + (ip[ 1 ] << 16 ) + (ip[ 2 ] << 8 ) + ip[ 3 ];
26 }
27
28 /// <summary>
29 /// 数据转IP地址
30 /// </summary>
31 /// <param name="uintIP"> 数据 </param>
32 /// <returns> IP地址 </returns>
33 public static String DataToIP( uint uintIP)
34 {
35 // 将10进制整数形式转换成127.0.0.1形式的IP地址
36 StringBuilder sb = new StringBuilder( "" );
37 sb.Append(Convert.ToString(uintIP >> 24 ));
38 sb.Append( " . " );
39 sb.Append(Convert.ToString((uintIP & 0x00FFFFFF ) >> 16 ));
40 sb.Append( " . " );
41 sb.Append(Convert.ToString((uintIP & 0x0000FFFF ) >> 8 ));
42 sb.Append( " . " );
43 sb.Append(Convert.ToString(uintIP & 0x000000FF ));
44 sb.Append( " . " );
45 return sb.ToString();
46 }
47 }
IP地址存储问题
最新推荐文章于 2024-07-20 22:45:51 发布