I have a .net core 2.0 project which is trying to get Host name and Host IP address from a linux machine. The program runs well in Mac OS and Windows but not on 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;
}
}
}
The exception I got is
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)
Any idea how to fix it or any alternative to get IP on a linux machine? Thanks.