Convert IPv4 To Number

Convert IPv4 To Number

Explains the code required to convert the given IPv4 Octets to Number and vice versa.

March 02, 2019

This post shows the code required to convert an IPv4 Address to Number and vice versa.

The below-mentioned lines convert an IPv4 Address to Long.

// IP
String ip = "192.168.1.1";

// IP Octets string array
String[] octets = ip.split( "\\." );

// IP Octets integer array
int[] octetsNum = new int[] {
Integer.parseInt( octets[ 0 ] ),
Integer.parseInt( octets[ 1 ] ),
Integer.parseInt( octets[ 2 ] ),
Integer.parseInt( octets[ 3 ] )
};

// IP in numeric form
long ipNum = ( octetsNum[ 0 ] * (int)Math.pow( 256, 3 ) ) + ( octetsNum[ 1 ] * (int)Math.pow( 256, 2 ) ) + ( octetsNum[ 2 ] * 256 ) + ( octetsNum[ 3 ] );

We can also convert the number back to IPv4 Address as shown below.

// IP in numeric form
long ipNum = -1062731519;

// Convert numeric IP to IPv4 Address
String ipAddr = ( ( ipNum >> 24 ) & 0xFF ) + "." + ( ( ipNum >> 16 ) & 0xFF ) + "." + ( ( ipNum >> 8 ) & 0xFF ) + "." + ( ipNum & 0xFF );

Below mentioned is the complete and tested code.

package networking;

public class IpUtil {

public static void main( String args[] ) {

// Stores the IP Address
String ipOctets = "192.168.1.1";

IpUtil ipUtil = new IpUtil();

// Convert IP to Number
long ipNum = ipUtil.ipToNum( ipOctets );

// Print the number
System.out.println( "The number of given IP Address : " + ipOctets + " is: " + ipNum );

// Convert Number back to IP
ipOctets = ipUtil.numToIp( ipNum );

// Print the IP
System.out.println( "The IP Address of given number : " + ipNum + " is: " + ipOctets );
}

/**
* Convert and return the given IP Octets to number.
*/
public long ipToNum( String ip ) {

long ipNum = -1;

// IP Octets string array
String[] octets = ip.split( "\\." );

// IP Octets integer array
int[] octetsNum = new int[] {
Integer.parseInt( octets[ 0 ] ),
Integer.parseInt( octets[ 1 ] ),
Integer.parseInt( octets[ 2 ] ),
Integer.parseInt( octets[ 3 ] )
};

// IP in numeric form
ipNum = ( octetsNum[ 0 ] * (int)Math.pow( 256, 3 ) ) + ( octetsNum[ 1 ] * (int)Math.pow( 256, 2 ) ) + ( octetsNum[ 2 ] * 256 ) + ( octetsNum[ 3 ] );

return ipNum;
}

public String numToIp( long ipNum ) {

// Convert numeric IP to IPv4 Address
String ipAddr = ( ( ipNum >> 24 ) & 0xFF ) + "." + ( ( ipNum >> 16 ) & 0xFF ) + "." + ( ( ipNum >> 8 ) & 0xFF ) + "." + ( ipNum & 0xFF );

return ipAddr;
}

}

The output should be the same as mentioned below.

The number of given IP Address : 192.168.1.1 is: -1062731519
The IP Address of given number : -1062731519 is: 192.168.1.1

Write a Comment
Click the captcha image to get new code.
Discussion Forum by DISQUS