Last active
December 12, 2015 08:39
-
-
Save yetanotherchris/4746180 to your computer and use it in GitHub Desktop.
NetworkUtils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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