Today I want to share this small, yet useful C# helper class that I still use when I need to retrieve, check or validate one or more IP Addresses registered on the Web Server. You can use it for a number of tasks/scenarios, including:
- Retrieve the first available IP Address of the Web Server machine hosting the Web Application.
- Retrieve a list of all the IPV4 and IPV6 Addresses registered on the Web Server machine hosting the Web Application.
- Check if a given IP Address is one of the IP Addresses registered on the Web Server.
The helper class was made some years ago, yet it can still be used on any ASP.NET project, including ASP.NET Forms, ASPX pages, ASP.NET MVC, ASP.NET Web API, ASP.NET WCF with any other framework versions & builds, up to the most recent ASP.NET Core.
Here it is: enjoy!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
namespace Ryadel.Components.Util { public static class NetworkUtil { /// <summary> /// Gets all the IP addresses of the server machine hosting the application. /// </summary> /// <returns>a string array containing all the IP addresses of the server machine</returns> public static IPAddress[] GetIPAddresses() { IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); // `Dns.Resolve()` method is deprecated. return ipHostInfo.AddressList; } /// <summary> /// Gets the IP address of the server machine hosting the application. /// </summary> /// <param name="num">if set, it will return the Nth available IP address: if not set, the first available one will be returned.</param> /// <returns>the (first available or chosen) IP address of the server machine</returns> public static IPAddress GetIPAddress(int num = 0) { return GetIPAddresses()[num]; } /// <summary> /// Checks if the given IP address is one of the IP addresses registered to the server machine hosting the application. /// </summary> /// <param name="ipAddress">the IP Address to check</param> /// <returns>TRUE if the IP address is registered, FALSE otherwise</returns> public static bool HasIPAddress(IPAddress ipAddress) { return GetIPAddresses().Contains(ipAddress); } /// <summary> /// Checks if the given IP address is one of the IP addresses registered to the server machine hosting the application. /// </summary> /// <param name="ipAddress">the IP Address to check</param> /// <returns>TRUE if the IP address is registered, FALSE otherwise</returns> public static bool HasIPAddress(string ipAddress) { return HasIPAddress(IPAddress.Parse(ipAddress)); } } } |
In case you also need to execute a ICMPv4 PING to a remote host, you can integrate within this class the PingHost method described in this other post.
One Comment on “ASP.NET C# Helper Class to get Web Server IP Address and other network-related methods”