views:

515

answers:

2

Hi, i'm need to calculate net mask and subnet addr using broadcast addr and host address from this subnet. I must use only bitwise operations not comparing of string representation, sysadmin tools and so on.

I have some formulas for calculating addresses. but i dont know, how using it with my source data.

  • ^ -- is bitwise xor
  • ~ -- negation
  • & and | conjunction and disjunction respectively
  • Formulas:
  • ip | (~m) = b
  • ip & m = n
  • n | (~m) = b
  • n ^ b = ~m

where n -- is subnet address, b -- broadcast address, ip -- host address from subnet and m -- is net mask.

(for example, i have 192.168.1.160 -- subnet addr, 192.168.1.191 -- broadcast, and /27 net mask (255.255.255.224))

Thanks for advice, and excuse my english :)

+1  A: 

Impossible. Suppose the broadcast is 192.168.1.255 and the address is 192.168.1.251. It can be 192.168.1.0/24, 192.168.1.128/25, 192.168.1.128/26, etc.

Michael Krelin - hacker
To begin with, i want to get a equal part of binary representation ip addr and broadcast. E.g. :1100000010101000110111111 (broadcast)1100000010101000110101100 (ip) have a equal part `11000000101010001101`. with trailing zeros it be subnet address. Moreover, i can calculate first bits of netmask by inverting result of (ip xor broadcast), but last bits contain trash values.
Golovko
Like I've shown in my example - the overlapping part of the broadcast and the actual ip address is not necessarily the network because most significant bits of the host part of the ip address may be 1s.
Michael Krelin - hacker
A: 

hacker's answer pretty much covers it, except that if you had a further condition such as "for the longest/shortest possible netmask". Or, if in fact the question is asking you to display all possible answers.

The operations you have specified are a bit limited if you want to create a loop solution. You would want some bitshift operations as well. Otherwise, you can run up to 32 separate tests, one for each of the possible netmasks. This snippet shows what I'm getting at, assuming that you want to print all solutions.

...
m = 255.0.0.0;
if ( ( b & m ) == ( ip & m ) )
{
    n = b & m;
    // Print out b, ip, n and m
}
m = 255.128.0.0;
...

If you want to print out shortest/longest answers, you will need to add variables to store best answer and/or flags to indicate whether or not an answer has been found.

By the way, in hacker's answer, I think the third example presented should be 192.168.1.192/26, not 192.168.1.128/26. Because the fourth byte of the address is all 1's, the network part of the address has to have all 1's in the fourth byte too.

Tony van der Peet