Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert four 32 bits ints to IP address in java

Using the code found here: https://libbits.wordpress.com/2011/05/17/check-if-ip-is-within-range-specified-in-cidr-in-java/

  // Step 1. Convert IPs into ints (32 bits). 
// E.g. 157.166.224.26 becomes 10011101  10100110  11100000 00011010
int addr = (( 157 << 24 ) & 0xFF000000) 
           | (( 166 << 16 ) & 0xFF0000) 
           | (( 224 << 8 ) & 0xFF00) 
           |  ( 26 & 0xFF);

// Step 2. Get CIDR mask
int mask = (-1) << (32 - 10);

// Step 3. Find lowest IP address
int lowest = addr & mask;

// Step 4. Find highest IP address
int highest = lowest + (~mask);

I'm able to split a string into four ints and create boundaries for my IP range. Now I want to be able to generate an ip that is between the highest and lowest values. For example: given the range: 157.166.224.26/10 I get an address of -1650008038 my lowest ip address is -1652555776 and highest ip address is -1648361473. Now I need to generate a number that is between my lowest and highest and convert it back to four integers, this last part is where I'm lost at, I'm not sure how to convert -1648361473 to an ip address

like image 329
user793491 Avatar asked Aug 20 '26 19:08

user793491


1 Answers

That's pretty easy. Let say the IPv4 address is in the ipaddr variable, you can write something like that:

byte[] addr = new byte[4];
addr[0] = (ipaddr >> 24) & 0xFF;
addr[1] = (ipaddr >> 16) & 0xFF;
addr[2] = (ipaddr >> 8 ) & 0xFF;
addr[3] = ipaddr & 0xFF;

InetAddress inetAddr = InetAddress.getByAddress(addr);
like image 189
tofcoder Avatar answered Aug 22 '26 08:08

tofcoder