Thursday, July 9, 2009

IP Subnets

A buddy of mine sent me an IM today asking for some help with a project. Specifically, he is working with an ISP and needed to write some code to determine all of the IP's in a CIDR subnet based on the network and broadcast addresses, which are stored in a SQL database as long's (using the php function ip2long for conversion).

After doing a little bit of research, the long values are simply the concatenation of the four 8-bit binary numbers then casted into one giant long value. This makes life simple, because concurrent IP's will also be concurrent in the long format. Not only are they concurrent, but they are sequential, so you can find out if an IP is in the network with simple conditional logic:

If( $networkaddr <= $ipaddr <= $broadcastaddr )

Because the database is storing all of these values as longs, the SQL query can be constructed with the simple conditional logic, with no additional logic. After figuring it all out, everything is pretty simple. The network address is going to be the lowest IP in the subnet and the broadcast is going to be the highest value in the subnet. Combine this with the relationship properties the converted IP's have when they are long values and its a pretty simple way to deal with things, just not intuitive.

No comments:

Post a Comment