Click here to Skip to main content
15,886,661 members
Articles / Programming Languages / C#

IP Address Extension

Rate me:
Please Sign up or sign in to vote.
4.54/5 (11 votes)
22 Sep 2010CPOL2 min read 30.1K   736   33   2
Some extension methods to determine whether an IP Address is from the intranet (The local network)

Introduction

Recently, I deployed an application that was only available on the local intranet to be available on the internet. In doing so, concerns were raised about the protection of the company's IP. The site is password protected, however, it was a requirement that some information be restricted when the site was not accessed from the local intranet. The users of the system and the people deemed to be of risk to steal company IP were deemed to be not technically savvy, so the solution did not have to be full proof. It was decided then that an effective yet relatively simple solution would to be check the IP address of the request and if were a private IP address, then the site would behave differently from if it was accessed from the premises of the company.

Background

Initially, I did some quick Google searches to find a solution online. However after 30 minutes of searching, I was surprised that I couldn't find one. Knowing that the solution would not take ample time to complete, I decided to stop searching and do some coding. Firstly, I needed to know what the private IP Addresses are. Wikipedia listed the following as private IP Addresses.

  • 10.0.0.0 – 10.255.255.255
  • 172.16.0.0 – 172.31.255.255
  • 192.168.0.0 – 192.168.255.255

The Code

To implement the solution, I decided to write a couple of extension methods for the IPAddress class. One of that does a bitwise AND of the IP address with another address and returns a new IP Address. The second method returns a bool determining whether the IP Address is from the intranet.

C#
public static IPAddress And(this IPAddress ipAddress, IPAddress mask)
{
  byte[] addressBytes;
  byte[] maskBytes;
  CheckIPVersion(ipAddress, mask, out addressBytes, out maskBytes);
  
  byte[] resultBytes = new byte[addressBytes.Length];
  for (int i = 0; i < addressBytes.Length; ++i)
  {
    resultBytes[i] = (byte)(addressBytes[i] & maskBytes[i]);
  }
  
  return new IPAddress(resultBytes);
}
C#
public static bool IsOnIntranet(this IPAddress ipAddress)
{
  if (empty.Equals(ipAddress))
  {
    return false;
  }
  bool onIntranet = IPAddress.IsLoopback(ipAddress);
  onIntranet = onIntranet || 
	ipAddress.Equals(ipAddress.And(intranetMask1)); //10.255.255.255
  onIntranet = onIntranet || 
	ipAddress.Equals(ipAddress.And(intranetMask4)); ////192.168.255.255
  
  onIntranet = onIntranet || (intranetMask2.Equals(ipAddress.And(intranetMask2))
    && ipAddress.Equals(ipAddress.And(intranetMask3)));
    
  return onIntranet;
}

The following are the definitions of the maks I used.

C#
private static IPAddress empty = IPAddress.Parse("0.0.0.0");
private static IPAddress intranetMask1 = IPAddress.Parse("10.255.255.255");
private static IPAddress intranetMask2 = IPAddress.Parse("172.16.0.0");
private static IPAddress intranetMask3 = IPAddress.Parse("172.31.255.255");
private static IPAddress intranetMask4 = IPAddress.Parse("192.168.255.255");

Using the Code

To use the code, simply pretend you are calling a method on the IPAddress class. For example:

C#
IPAddress address = IPAddress.Parse("10.20.10.5");
bool onTheIntranet = address.IsOnIntranet());

Nunit Tests

I've included some nunit tests in the code files as a check to make sure the calculations are correct. It took a little while to work out what I needed to AND together to come up with the correct result, so if I messed up be sure to let me know so I can fix up the code.

History

  • 23rd September, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Australia Australia
I am currently a Software Engineer working for an international company on a defence project. I graduated from university in 2001 with a Bacehlor of Engineering (Aerospace Avionics) First Class Honours. Currently in my spare time I am experimenting with the joys of shareware. I also enjoy most sports including, basketball, netball and rockclimbing.
www.s3ware.com
www.s3search.com.au
Civic Shower Screens

Comments and Discussions

 
QuestionFixed IPv6 Compatibility and Redundant check. Pin
jfriedman1-Feb-15 8:52
jfriedman1-Feb-15 8:52 
Your code was double checking onIntranet when IsLoopback determined this first.

It also seems your code was not working when the address families did not match.

I fixed these two problems below.

Regards,
v//



C#
/// <summary>
/// Retuns true if the ip address is one of the following
/// IANA-reserved private IPv4 network ranges (from http://en.wikipedia.org/wiki/IP_address)
///  Start        End
///  10.0.0.0       10.255.255.255
///  172.16.0.0       172.31.255.255
///  192.168.0.0   192.168.255.255
/// </summary>
/// <returns></returns>
public static bool IsOnIntranet(this IPAddress ipAddress)
{
    if (empty.Equals(ipAddress))
    {
        return false;
    }

    bool onIntranet = IPAddress.IsLoopback(ipAddress);

    if (false == onIntranet)
    {
        //Handle IPv6 by getting the IPv4 Mapped Address.
        if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
        {
            onIntranet = ipAddress.Equals(ipAddress.And(intranetMask1.MapToIPv6())); //10.255.255.255
            onIntranet = onIntranet || ipAddress.Equals(ipAddress.And(intranetMask4.MapToIPv6())); ////192.168.255.255

            onIntranet = onIntranet || (intranetMask2.Equals(ipAddress.And(intranetMask2.MapToIPv6()))
              && ipAddress.Equals(ipAddress.And(intranetMask3.MapToIPv6())));
        }
        else
        {
            onIntranet = ipAddress.Equals(ipAddress.And(intranetMask1)); //10.255.255.255
            onIntranet = onIntranet || ipAddress.Equals(ipAddress.And(intranetMask4)); ////192.168.255.255

            onIntranet = onIntranet || (intranetMask2.Equals(ipAddress.And(intranetMask2))
              && ipAddress.Equals(ipAddress.And(intranetMask3)));
        }


    }

    return onIntranet;
}

GeneralMy vote of 5 Pin
fredatcodeproject2-Sep-13 21:34
professionalfredatcodeproject2-Sep-13 21:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.