Search code examples
.netc#-4.0windows-server-2008ipv4subnet

Determine IPv4 Subnet Mask in C#


As I have to setup quite a few Windows Server machines, I decided to write a little program in C# to help simplify some of these tasks. The last one I have to add is the ability to input an IP Range (74.117.238.112/28 for example) and have it automatically add all of these as static IP's to the NIC.

I have always used web calculators in the past for this, however I am trying to figure out how to do it programmatically in C#. I have found this write-up HERE, which makes a lot of sense (learned a bit from it) but is a bit confusing. The calculators I have used in the past presented me with Subnet masks like 255.255.255.240, or .248, where as this only seems to return one of four values.

Is this code example correct, or will it need to be modified further to actually be usable?


Solution

  • the link you mentioned gives you standard subnet masks for different IP classes. This is not really subnetting.

    If I understand you correctly, you only need the subnet mask, which is only dependent on the subnet (/28 in your example) and not the ip address.

    I wrote this small function::

        public static string GetSubnetMask(byte subnet)
        {
            long mask = (0xffffffffL << (32-subnet)) & 0xffffffffL;
            mask=IPAddress.HostToNetworkOrder((int)mask);
            return new IPAddress((UInt32)mask).ToString();
        }
    

    If you call it with a subnet (e.g. 28) it will return the subnet as a string (255.255.255.240).

    Tell me if this is what you needed or if there is anything else.