How to Convert IP Address to Decimal in Java


In this example, we will learn how to convert IP address to Decimal Number in Java.

Source Code

package com.beginner.examples;

public class IPToDecimal {

	public static void main(String[] args) {
		
		long result = ipToLong("192.168.1.2");
		System.out.println(result); 

	}
	
	public static long ipToLong(String ip) {
		String[] arr = ip.split("\.");
		long result = 0;
		for (int i = 0; i <= 3; i++) {
			long ip2 = Long.parseLong(arr[i]);
			result |= ip2 << ((3-i) << 3);
		}
		return result;
	}
}

Output:

3232235778
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments