this is what im trying to code a
simple Subnet Calculator for Class C IPv4 addresses.
The calculator should calculate subnet information for specified IPv4
Class
C network addresses only (ignore Class A and B). The user should input
the
IP address for the Class C network, the number of network bits in the
address (since it could be a subnetted address already), and the number
of
bits to borrow for subnetting.
e.g.
192.168.10.0 - Class C IP network address
24 - number of network bits in address
2 - number of bits to borrow
dont no if this will help anyone..
but all help is welcome
Well, if I understand you right, you get a 255.255.255.0 subnet (24 bits).
What do you mean by 2 bits to borrow? 2 bits out of the last 8-bit range?
In that case you will get
11111111.11111111.11111111.11000000 = 255.255.255.192
Consider the ip address as a 32 bit long number. 24+2 is 26 bits
If you put -1 in an integer you will get the number
11111111111111111111111111111111
Push this number left as many positions as you lack to get full 32 bits
int n = -1;
n <<= (32 - 26);
n is now
11111111111111111111111111000000
You can convert this number back to a subnet string by splitting it in
chunks of 8 bytes
We can do that by using AND (&) with 11111111 (255)
11111111111111111111111111000000
& 00000000000000000000000011111111
= 00000000000000000000000011000000 = 192
n & 255
Push the number right 8 bits and we get
n >>= 8;
00000000111111111111111111111111 (->11000000)
& 00000000000000000000000011111111
= 00000000000000000000000011111111 = 255
In the end you will have something like
int n = -1;
n <<= (32 - networkbits - borrowedbits);
string subnet = (n & 255).ToString();
n >>= 8;
subnet = (n & 255) + "." + subnet;
n >>= 8;
subnet = (n & 255) + "." + subnet;
n >>= 8;
subnet = (n & 255) + "." + subnet;
subnet is now "255.255.255.192"