Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Checking for Local IP Address in C#

How the things will be?
1.Get the host name first by Dns.GetHostName();
2. Save the IP address in IPHostEntry by Dns.GetHostByName(hostName);
3. Using IPAddress array, get the actual host address.
4. Using IPAddress array, get the host address of local.
5. Compare the results of step 3 and 4.

For example, we are getting our local host and sending for the check.
You can check with the other remote IPs also by passing remote host while calling the bool method.
  1. using System;
  2. using System.Net;
  3.  
  4. public class ForgetCode
  5. {
  6. static string IPHost;
  7. public static void Main()
  8. {
  9. UseDNS();
  10. }
  11.  
  12. public static void UseDNS()
  13. {
  14. string hostName = Dns.GetHostName();
  15. IPHostEntry local = Dns.GetHostByName(hostName);
  16. foreach (IPAddress ipaddress in local.AddressList)
  17. {
  18. IPHost = ipaddress.ToString();
  19. }
  20.  
  21. if (isLocal(IPHost))
  22. {
  23. Console.WriteLine("Yes, it is a local system");
  24. }
  25. else
  26. {
  27. Console.WriteLine("No, it is not a local system");
  28. }
  29.  
  30. }
  31.  
  32. public static bool isLocal(string host)
  33. {
  34. try
  35. {
  36. IPAddress[] hostIPs = Dns.GetHostAddresses(host);
  37. // get local IP addresses
  38. IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
  39.  
  40. // test if any host IP equals to any local IP or to localhost
  41. foreach (IPAddress hostIP in hostIPs)
  42. {
  43. // is localhost
  44. if (IPAddress.IsLoopback(hostIP)) return true;
  45. // is local address
  46. foreach (IPAddress localIP in localIPs)
  47. {
  48. if (hostIP.Equals(localIP)) return true;
  49. }
  50. }
  51. }
  52. catch { }
  53. return false;
  54. }
  55. }


If it is a local IP address then the output will be
Yes, it is a local system