public void GetLocalIp() { if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true) { System.Net.NetworkInformation.NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); foreach (System.Net.NetworkInformation.NetworkInterface ni in interfaces) { //以下代码不能处理网络是否识别了只要有IP地址,都通过了 if (ni.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up&ni.NetworkInterfaceType!=NetworkInterfaceType.Tunnel&ni.NetworkInterfaceType!=NetworkInterfaceType.Loopback) { System.Net.NetworkInformation.IPInterfaceProperties property = ni.GetIPProperties(); foreach (System.Net.NetworkInformation.UnicastIPAddressInformation ip in property.UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { cmbLocalIP.Text = ip.Address.ToString(); } } } } } else { MessageBox.Show("没检测到能联网的网卡,请检查网卡状态!"); } }
如果是获取本机的IP的话,这样获取公网IP其实效率也挺低的。 可以用如下代码: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { IPHostEntry ipHostEntry = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in ipHostEntry.AddressList) { Console.WriteLine("{0}:{1}", ip.AddressFamily, ip.ToString()); } } } }这个代码可以把所有本机用到的IP,包括IPv4,IPv6都找出来。
{
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true)
{
System.Net.NetworkInformation.NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
foreach (System.Net.NetworkInformation.NetworkInterface ni in interfaces)
{
//以下代码不能处理网络是否识别了只要有IP地址,都通过了
if (ni.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up&ni.NetworkInterfaceType!=NetworkInterfaceType.Tunnel&ni.NetworkInterfaceType!=NetworkInterfaceType.Loopback)
{
System.Net.NetworkInformation.IPInterfaceProperties property = ni.GetIPProperties();
foreach (System.Net.NetworkInformation.UnicastIPAddressInformation ip in
property.UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
cmbLocalIP.Text = ip.Address.ToString();
}
}
}
}
}
else
{
MessageBox.Show("没检测到能联网的网卡,请检查网卡状态!");
}
}
可以用如下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
IPHostEntry ipHostEntry = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in ipHostEntry.AddressList)
{
Console.WriteLine("{0}:{1}", ip.AddressFamily, ip.ToString());
}
}
}
}这个代码可以把所有本机用到的IP,包括IPv4,IPv6都找出来。
这个里面有相关代码