C#获取本机IP(排除IPV6,仅获取IPV4)的方法

using System;
 using System.Text;
 using System.Windows.Forms;
 using System.Net;
 using System.Net.Sockets;
 using System.Collections.Specialized;
 
 namespace GetIpv4Test
 {
     public partial class Form1 : Form
     {
         public Form1()
         {
             InitializeComponent();
             ShowIP();
         }
         void ShowIP()
         {
             //ipv4地址也可能不止一个
             foreach (string ip in GetLocalIpv4())
             {
                 this.richTextBoxIPv4.AppendText(ip.ToString());
             }
             return;
         }
         string[] GetLocalIpv4()
         {
             //事先不知道ip的个数,数组长度未知,因此用StringCollection储存
             IPAddress[] localIPs;
             localIPs = Dns.GetHostAddresses(Dns.GetHostName());
             StringCollection IpCollection = new StringCollection();
             foreach (IPAddress ip in localIPs)
             {
                 //根据AddressFamily判断是否为ipv4,如果是InterNetWorkV6则为ipv6
                 if (ip.AddressFamily == AddressFamily.InterNetwork)
                     IpCollection.Add(ip.ToString());
             }
             string[] IpArray = new string[IpCollection.Count];
             IpCollection.CopyTo(IpArray, 0);
             return IpArray;
         }
     }
 }


你可能感兴趣的:(C#获取本机IP(排除IPV6,仅获取IPV4)的方法)