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 |
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Text; using System.Threading.Tasks; namespace Ryadel.Components.Util { public static class NetworkUtil { /// <summary> /// Executes an ICMPv4 PING and returns TRUE if the attempt succeedes, FALSE otherwise /// </summary> /// <param name="nameOrAddress">IPv4 or Hostname</param> /// <returns>TRUE if the given IP/Hostname responds to the ping attempt, FALSE otherwise</returns> public static bool PingHost(string nameOrAddress, bool throwExceptionOnError = false) { bool pingable = false; using (Ping pinger = new Ping()) { try { PingReply reply = pinger.Send(nameOrAddress); pingable = reply.Status == IPStatus.Success; } catch (PingException e) { if (throwExceptionOnError) throw e; pingable = false; } } return pingable; } } } |
In case you also need to retrieve IP Address(es) of the Web Server machine hosting the Web Application and/or check if a given IP Address is registered on the Web Server or not, you can integrate within this class the GetIPAddress, GetIPAddresses and HasIPAddress methods described in this other post.