Joh*_*ann 29 c# ip-address ipv4
如何从中获取Internet协议版本4地址Dns.GetHostAddresses()?我有下面的代码,它给我IPv4和IPv6地址.我必须使用具有多个IPv4地址的盒子.
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
private void get_IPs()
{
foreach (IPAddress a in localIPs)
{
server_ip = server_ip + a.ToString() + "/";
}
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*ary 36
来自我的博客:
/// <summary>
/// This utility function displays all the IP (v4, not v6) addresses of the local computer.
/// </summary>
public static void DisplayIPAddresses()
{
StringBuilder sb = new StringBuilder();
// Get a list of all network interfaces (usually one per network card, dialup, and VPN connection)
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface network in networkInterfaces)
{
// Read the IP configuration for each network
IPInterfaceProperties properties = network.GetIPProperties();
// Each network interface may have multiple IP addresses
foreach (IPAddressInformation address in properties.UnicastAddresses)
{
// We're only interested in IPv4 addresses for now
if (address.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
// Ignore loopback addresses (e.g., 127.0.0.1)
if (IPAddress.IsLoopback(address.Address))
continue;
sb.AppendLine(address.Address.ToString() + " (" + network.Name + ")");
}
}
MessageBox.Show(sb.ToString());
}
Run Code Online (Sandbox Code Playgroud)
特别是,我不建议Dns.GetHostAddresses(Dns.GetHostName());,不管这条线在各种文章和博客上有多受欢迎.
Joo*_*tse 28
在你的代码中添加这样的东西
if( IPAddress.Parse(a).AddressFamily == AddressFamily.InterNetwork )
// IPv4 address
Run Code Online (Sandbox Code Playgroud)
Joe*_*Joe 11
这是我使用的一个功能:
public static string GetIP4Address()
{
string IP4Address = String.Empty;
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily == AddressFamily.InterNetwork)
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
Run Code Online (Sandbox Code Playgroud)
作为一个可枚举的:
public static IEnumerable<string> GetIP4Addresses()
{
return Dns.GetHostAddresses(Dns.GetHostName())
.Where(IPA => IPA.AddressFamily == AddressFamily.InterNetwork)
.Select(x => x.ToString());
}
Run Code Online (Sandbox Code Playgroud)
使用Linq时非常干净和甜美
IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName()).Where(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToArray();
Run Code Online (Sandbox Code Playgroud)