NetworkUtils
using System; | |
using System.Security; | |
using System.Net; | |
using System.Net.Sockets; | |
namespace Demo | |
{ | |
public class NetworkUtils | |
{ | |
/// <summary> | |
/// Performs a hostname lookup from an IP. | |
/// </summary> | |
/// <param name="Ip"></param> | |
/// <returns></returns> | |
public static string GetHostnameFromIp(string Ip) | |
{ | |
string hostname = ""; | |
try | |
{ | |
IPHostEntry ipHostEntry = Dns.GetHostByAddress(Ip); | |
hostname = ipHostEntry.HostName; | |
} | |
catch (FormatException) | |
{ | |
hostname = "Please specify a valid IP address."; | |
return hostname; | |
} | |
catch (SocketException) | |
{ | |
hostname = "Unable to perform lookup - a socket error occured."; | |
return hostname; | |
} | |
catch (SecurityException) | |
{ | |
hostname = "Unable to perform lookup - permission denied."; | |
return hostname; | |
} | |
catch (Exception) | |
{ | |
hostname = "An unspecified error occured."; | |
return hostname; | |
} | |
return hostname; | |
} | |
/// <summary> | |
/// Performs an IP lookup from a hostname. | |
/// </summary> | |
/// <param name="Hostname"></param> | |
/// <returns></returns> | |
public static string GetIpFromHostname(string Hostname) | |
{ | |
string ip = ""; | |
try | |
{ | |
IPHostEntry ipHostEntry = Dns.Resolve(Hostname); | |
if ( ipHostEntry.AddressList.Length > 0 ) | |
{ | |
//ip = ipHostEntry.AddressList[0].Address.ToString(); | |
ip = ipHostEntry.AddressList[0].ToString(); | |
} | |
else | |
{ | |
ip = "No information found."; | |
} | |
} | |
catch ( SocketException ) | |
{ | |
ip = "Unable to perform lookup - a socket error occured."; | |
return ip; | |
} | |
catch ( SecurityException ) | |
{ | |
ip = "Unable to perform lookup - permission denied."; | |
return ip; | |
} | |
catch ( Exception ) | |
{ | |
ip = "An unspecified error occured."; | |
return ip; | |
} | |
return ip; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment