1 [StructLayout(LayoutKind.Explicit)]
2 public struct IP
3 {
4 public IP(UInt32 value)
5 {
6 this._text1 = 0;
7 this._text2 = 0;
8 this._text3 = 0;
9 this._text4 = 0;
10 this._value = value;
11 }
12 public IP(Byte text1, Byte text2, Byte text3, Byte text4)
13 {
14 this._value = 0;
15 this._text1 = text1;
16 this._text2 = text2;
17 this._text3 = text3;
18 this._text4 = text4;
19 }
20 [FieldOffset(0)]
21 private UInt32 _value;
22 [FieldOffset(0)]
23 private Byte _text1;
24 [FieldOffset(1)]
25 private Byte _text2;
26 [FieldOffset(2)]
27 private Byte _text3;
28 [FieldOffset(3)]
29 private Byte _text4;
30
31 public UInt32 Value
32 {
33 get { return this._value; }
34 set { this._value = value; }
35 }
36 public Byte Text1
37 {
38 get { return this._text1; }
39 set { this._text1 = value; }
40 }
41 public Byte Text2
42 {
43 get { return this._text2; }
44 set { this._text2 = value; }
45 }
46 public Byte Text3
47 {
48 get { return this._text3; }
49 set { this._text3 = value; }
50 }
51 public Byte Text4
52 {
53 get { return this._text4; }
54 set { this._text4 = value; }
55 }
56
57 public override string ToString()
58 {
59 return String.Format("{0}.{1}.{2}.{3}", this._text1.ToString(), this._text2.ToString(),
60 this._text3.ToString(), this._text4.ToString());
61 }
62
63 public static implicit operator IP(UInt32 value)
64 {
65 return new IP(value);
66 }
67 public static explicit operator UInt32(IP ip)
68 {
69 return ip._value;
70 }
71 }
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 IP ip = new IP(192,168,1,1);
6 Console.WriteLine(ip);
7 UInt32 value = (UInt32)ip;
8 Console.WriteLine(value);
9 Console.WriteLine(ip.Value);
10 IP ip2 = (IP)(1234567);
11 Console.WriteLine(ip2);
12
13 Console.ReadKey();
14 }
15 }

1、IP地址转换为整数
原理:IP地址每段可以看成是8位无符号整数即0-255,把每段拆分成一个二进制形式组合起来,然后把这个二进制数转变成
一个无符号32为整数。
举例:一个ip地址为10.0.3.193
每段数字 相对应的二进制数
10 00001010
0 00000000
3 00000011
193 11000001
组合起来即为:00001010 00000000 00000011 11000001,转换为10进制就是:167773121,即该IP地址转换后的数字就是它了。
public static long ip2int(String ip) {
String[] items = ip.split("\\.");
return Long.valueOf(items[0]) < < 24
| Long.valueOf(items[1]) << 16
| Long.valueOf(items[2]) << 8 | Long.valueOf(items[3]);
}
2、整数转换为IP地址
原理:把这个整数转换成一个32位二进制数。从左到右,每8位进行一下分割,得到4段8位的二进制数,把这些二进制数转换成整数然后加上”.”就是这个ip地址了
举例:167773121
二进制表示形式为:00001010 00000000 00000011 11000001
分割成四段:00001010,00001010,00000011,11000001,分别转换为整数后加上“.”就得到了10.0.3.193。
public static String int2ip(long ipInt) {
StringBuilder sb = new StringBuilder();
sb.append(ipInt & 0xFF).append(".");
sb.append((ipInt >> 8) & 0xFF).append(".");
sb.append((ipInt >> 16) & 0xFF).append(".");
sb.append((ipInt >> 24) & 0xFF);
return sb.toString();
}