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.
Get answer from another thread Get local IP address which works for me
Thanks for the solution from @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;
}
User contributions licensed under CC BY-SA 3.0