我有一个 .net core 2.0 项目,它试图从 linux 机器上获取主机名和主机 IP 地址。该程序在 Mac OS 和 Windows 上运行良好,但在 linux - Ubuntu 16.04 上运行不佳
public class Program
{
public static void Main(string[] args)
{
var HostName = Dns.GetHostName();
Console.WriteLine("Host name : " + HostName);
var HostAddress = GetHostAddress(HostName);
Console.WriteLine("Host address : " + HostAddress);
}
private static string GetHostAddress(string hostName)
{
try
{
var addressList = Dns.GetHostAddresses(hostName);
foreach (IPAddress address in addressList)
{
Console.WriteLine("IP Address : " + address.ToString());
if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
string ip = address.ToString();
if (!ip.StartsWith("127."))
return ip;
}
}
return "127.0.0.1";
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
我得到的异常是
ubuntu@ip-10-40-121-185:~/home/IP$ dotnet IP.dll
Host name : ip-10-40-121-185
System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (0x00000005): No such device or address
at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)
at System.Net.Dns.GetHostAddresses(String hostNameOrAddress)
at IP.Program.GetHostAddress(String hostName) in /Users/jliu/RiderProjects/IpTest/IP/Program.cs:line 34
Unhandled Exception: System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: No such device or address
at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)
at System.Net.Dns.GetHostAddresses(String hostNameOrAddress)
at IP.Program.GetHostAddress(String hostName) in /Users/jliu/RiderProjects/IpTest/IP/Program.cs:line 52
at IP.Program.Main(String[] args) in /Users/jliu/RiderProjects/IpTest/IP/Program.cs:line 20 Aborted (core dumped)
知道如何修复它或在 Linux 机器上获取 IP 的任何替代方法吗? 谢谢。
最佳答案
从另一个线程获取答案 Get local IP address这对我有用
感谢@Gerardo H 提供的解决方案 https://stackoverflow.com/a/28621250/4861127
internal static string GetLocalIPv4(NetworkInterfaceType _type)
{
string output = "";
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties adapterProperties = item.GetIPProperties();
if (adapterProperties.GatewayAddresses.FirstOrDefault() != null)
{
foreach (UnicastIPAddressInformation ip in adapterProperties.UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
output = ip.Address.ToString();
}
}
}
}
}
return output;
}
关于c# - Dns.GetHostAddress(主机名)在 Ubuntu 16.04 中没有这样的设备或地址异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50365292/