QuietLeni
QuietLeni

Reputation: 137

Calculating a Subnet number from an IP Address and Subnet Mask in C#

I have a task to complete in C#. I have an:

IP Address: 192.168.1.57 and a Subnet Mask: 255.255.0.0

I need to find the Subnet number, which would be, in this case, 192.168.0.0.

However, I need to be able to do this in C# WITHOUT the use of the System.Net library (the system I am programming in does not have access to this library).

It seems like the process should be something like:

1) Split the IP Address into Octets

2) Split the Subnet Mask into Octets

3) Subnet Number Octet 1 = IP Address Octet 1 Anded with Subnet Mask Octet 1

4) Subnet Number Octet 2 = IP Address Octet 2 Anded with Subnet Mask Octet 2

5) Subnet Number Octet 3 = IP Address Octet 3 Anded with Subnet Mask Octet 3

6) Subnet Number Octet 4 = IP Address Octet 4 Anded with Subnet Mask Octet 4

7) Join the Subnet Number Octet 1 + . + Subnet Number Octet 2 + . + Subnet Number Octet 3 + . + Subnet Number Octet 4

8) Voila!

However, my C# is pretty poor. Does anyone have the C# knowledge to help?

Upvotes: 1

Views: 11644

Answers (2)

Rotem
Rotem

Reputation: 21947

This should accomplish the procedure you described.

string ipAddress = "192.168.1.57";
string subNetMask = "255.255.0.0";

string[] ipOctetsStr = ipAddress.Split('.');
string[] snOctetsStr = subNetMask.Split('.');

if (ipOctetsStr.Length != 4 || snOctetsStr.Length != 4)
{
   throw new ArgumentException("Invalid input strings.");
}

string[] resultOctets = new string[4];
for (int i = 0; i < 4; i++) 
{
    byte ipOctet = Convert.ToByte(ipOctetsStr[i]);
    byte snOctet = Convert.ToByte(snOctetsStr[i]);
    resultOctets[i] = (ipOctet & snOctet).ToString();
}

string resultIP = string.Join(".", resultOctets);

Upvotes: 5

dbasnett
dbasnett

Reputation: 11773

Forgive my VB code, but it is almost identical:

    Dim foo As Net.IPAddress = Net.IPAddress.Parse("192.168.1.57")
    Dim bar As Net.IPAddress = Net.IPAddress.Parse("255.255.0.0")

    Dim fooA() As Byte = foo.GetAddressBytes
    Dim barA() As Byte = bar.GetAddressBytes

    Array.Reverse(fooA)
    Array.Reverse(barA)

    Dim fooNum As Integer = BitConverter.ToInt32(fooA, 0)
    Dim barNum As Integer = BitConverter.ToInt32(barA, 0)

    Dim netNum As Integer = fooNum And barNum
    Dim netNumA() As Byte = BitConverter.GetBytes(netNum)
    Array.Reverse(netNumA)

    Dim subNet As New Net.IPAddress(netNumA)

Upvotes: 1

Related Questions