In the example code below could someone walk through a more detailed explanation of exactly what the lines below are actually doing like you'd explain it to a beginning developer.
for (byte octet : octets) {
result <<= 8;
result |= octet & 0xff;
}
public class Example {
public static long ipToLong(InetAddress ip) {
byte[] octets = ip.getAddress();
long result = 0;
for (byte octet : octets) {
result <<= 8;
result |= octet & 0xff;
}
return result;
}
public static void main(String[] args) throws UnknownHostException {
long ipLo = ipToLong(InetAddress.getByName("192.200.0.0"));
long ipHi = ipToLong(InetAddress.getByName("192.255.0.0"));
long ipToTest = ipToLong(InetAddress.getByName("192.200.3.0"));
System.out.println(ipToTest >= ipLo && ipToTest <= ipHi);
}
}
byte[] octets = ip.getAddress(); -> stores entire IP address as byte array
for (byte octet : octets) {} -> splits the byte-array into octets and iterates over them
result <<= 8 (shorthand for result = result<<8) -> Left-shift 8 bits shifts the result in binary by 8 bits, and adds 8 trailing zeros. (Multiplies the value of result by 2^8)
result |= octet & 0xff; (same as result|=octet which is shorthand for result = result | or octect -> Bitwise ORing, same as addition in this case, because we have 8 zeros at the end of result, after the previous step.
EDIT (thanks to @jtahlborn) -> the bitwise-anding with 0xFF is necessary to avoid sign extension when the byte is converted to an int.
Example
192.200.3.0 is the IP address in question. The final value is
This is generated in the following manner
192*(2^24) + 200*(2^16) + 3*(2^8) + 0*(2^0)
3221225472 + 13107200 + 768 = 3234333440
Now your code does the same, but using bitwise shifts
192 in binary is 11000000. First, it is added to result = 0;
result is now 11000000.
Then it is shifted left by 8 bits (effectively multiplying it by 2^8)
result is 11000000 00000000
Now, binary value of 200, which is 11001000 is added, making result now 11000000 11001000
This process is carried on, till you have the following 32 bit number,
11000000 11001000 00000011 00000000 which translates to the same 3234333440
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With