1 using System;
2 using System.Text;
3 using System.Windows.Forms;
4 using System.Net;
5 using System.Net.Sockets;
6 using System.Collections.Specialized;
7
8 namespace GetIpv4Test
9 {
10 public partial class Form1 : Form
11 {
12 public Form1()
13 {
14 InitializeComponent();
15 ShowIP();
16 }
17 void ShowIP()
18 {
19 //ipv4地址也可能不止一个
20 foreach (string ip in GetLocalIpv4())
21 {
22 this.richTextBoxIPv4.AppendText(ip.ToString());
23 }
24 return;
25 }
26 string[] GetLocalIpv4()
27 {
28 //事先不知道ip的个数,数组长度未知,因此用StringCollection储存
29 IPAddress[] localIPs;
30 localIPs = Dns.GetHostAddresses(Dns.GetHostName());
31 StringCollection IpCollection = new StringCollection();
32 foreach (IPAddress ip in localIPs)
33 {
34 //根据AddressFamily判断是否为ipv4,如果是InterNetWorkV6则为ipv6
35 if (ip.AddressFamily == AddressFamily.InterNetwork)
36 IpCollection.Add(ip.ToString());
37 }
38 string[] IpArray = new string[IpCollection.Count];
39 IpCollection.CopyTo(IpArray, 0);
40 return IpArray;
41 }
42 }
43 }