//NetIf.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
namespace Xxxxx
{
class NetIf
{
public struct NetIfType
{
public string netIf;
public string Ip;
}
public static List<NetIfType> NetIfList = new List<NetIfType>();
public static int selectNetIf = 0;
public static List<NetIfType> GetNetIf()
{
List<NetIfType> listStr = new List<NetIfType>();
//获取所有网卡信息
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
//判断是否为以太网卡
//Wireless80211 无线网卡 Ppp 宽带连接
//Ethernet 以太网卡
if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
//获取以太网卡网络接口信息
IPInterfaceProperties ip = adapter.GetIPProperties();
//获取单播地址集
UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
foreach (UnicastIPAddressInformation ipadd in ipCollection)
{
//InterNetwork IPV4地址 InterNetworkV6 IPV6地址
//Max MAX 位址
if (ipadd.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
listStr.Add(new NetIfType()
{
netIf = adapter.Description,
Ip = ipadd.Address.ToString()
});
}
}
}
}
return listStr;
}
//选择网卡上的本地IP
public static string GetLocalIp(int index)
{
if (index>= 0)
{
return NetIfList[index].Ip;
}
else
{
return null;
}
}
}
}
private void comboBoxNetIf_DropDown(object sender, EventArgs e)
{
NetIf.NetIfList.Clear();
NetIf.NetIfList = NetIf.GetNetIf();
comboBoxNetIf.Items.Clear();
foreach (NetIf.NetIfType m in NetIf.NetIfList)
{
comboBoxNetIf.Items.Add(m.netIf);
}
}
//在非UI线程中
private void UserThread()
{
string localIp = null;
int flag;
Invoke((EventHandler)(delegate
{
NetIf.selectNetIf = comboBoxNetIf.SelectedIndex;
}));
localIp = NetIf.GetLocalIp(NetIf.selectNetIf);
.......
}
实际效果: