码迷,mamicode.com
首页 > Windows程序 > 详细

C#获取IPv4代码

时间:2016-09-06 12:21:13      阅读:335      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GetIPv4Application
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_getIPv4_Click(object sender, EventArgs e)
        {
            ShowIP();
        }
        void ShowIP()
        {
            richTextBoxIPv4.Text = string.Empty;
            //ipv4地址也可能不止一个  
            foreach (string ip in GetLocalIpv4())
            {
                this.richTextBoxIPv4.AppendText(ip.ToString()+"\n");
            }
            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;
        }
    }
}

  技术分享

注:当有虚拟网卡时会获取到多个ip地址。

C#获取IPv4代码

标签:

原文地址:http://www.cnblogs.com/wuhailong/p/5844997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!