Finding subnet mask from IP4 address using c#.

IP4 addresses are categorized into 5 classes. For the  first three classes we have predefined subnet mask. So if we can detect the class of an IP address , we can determine the corresponding subnet mask. The address ranges used for each class are given in the following table (Taken from wiki):

Class

Leading bits

Start

End

CIDR
suffix

Default
subnet mask

Class A

    0

    0.0.0.0

127.255.255.255

   /8

255.0.0.0

Class B

    10

128.0.0.0

191.255.255.255

   /16

255.255.0.0

Class C

    110

192.0.0.0

223.255.255.255

   /24

255.255.255.0

Class D

    1110

224.0.0.0

239.255.255.255

   /4

not defined

Class E

    1111

240.0.0.0

255.255.255.255

   /4

not defined

To implement so, a class named IPClassTester has been written. The class has two methods: ReturnSubnetmask, ReturnFirtsOctet. The first one takes an IP address and return its corresponding subnet mask. For this it first extracts the first octet of the IP address using the method named ReturnFirtsOctet and then checks the first octet value with the IP4 class information and returns the corresponding subnet mask on match.

   1: class IPClassTester
   2: {
   3:    static public string ReturnSubnetmask(String ipaddress)
   4:    {
   5:       uint firstOctet =  ReturnFirtsOctet(ipaddress);
   6:       if (firstOctet >= 0 && firstOctet <= 127)
   7:           return "255.0.0.0";
   8:       else if (firstOctet >= 128 && firstOctet <= 191)
   9:           return "255.255.0.0";
  10:       else if (firstOctet >= 192 && firstOctet <= 223)
  11:           return "255.255.255.0";
  12:       else return "0.0.0.0";
  13:    }
  14:  
  15:    static public uint  ReturnFirtsOctet(string ipAddress)
  16:    {
  17:        System.Net.IPAddress iPAddress = System.Net.IPAddress.Parse(ipAddress);
  18:        byte[] byteIP = iPAddress.GetAddressBytes();
  19:        uint ipInUint = (uint)byteIP[0];     
  20:        return ipInUint;
  21:    }
  22: }

Hope this will save some of your time.

No Comments