//获取说有网卡信息
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 == AddressFamily.InterNetwork)
//判断是否为ipv4
Console.WriteLine(ipadd.Address.ToString());//获取ip
}
}
}
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());//获取所有IP
foreach (IPAddress ip in ips)
{
//如果IP为ip4地址,AddressFamily.InterNetwork就是IP 版本 4 的地址
if (ip.AddressFamily.Equals(AddressFamily.InterNetwork))
{
cbbIpAddress.Items.Add(ip.ToString());
}
}
然后你可以根据网关去区分,代码如下:
//添加System.Management引用
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection nics = mc.GetInstances();
foreach (ManagementObject nic in nics)
{
if (Convert.ToBoolean(nic["ipEnabled"]) == true)
{
Console.WriteLine((nic["IPAddress"] as String[])[0]);
Console.WriteLine((nic["IPSubnet"] as String[])[0]); //掩码
Console.WriteLine((nic["DefaultIPGateway"] as String[])[0]);//网关
}
}
你这是因为有两块网卡,实际中,你可以弹出一个窗口,让用户自己去选择要用哪个。
取内网的?那就判断192开头的。