ip To Number - Java Network

Java examples for Network:IP Address

Description

ip To Number

Demo Code


import java.util.ArrayList;
import java.util.regex.Pattern;

public class Main{
    public static void main(String[] argv) throws Exception{
        String ipAddr = "java2s.com";
        System.out.println(ipToNumber(ipAddr));
    }/*from   w  w  w .  j a va2 s.c  o m*/
    public static long ipToNumber(String ipAddr)
            throws InvalidIPAddressException {
        if (ipAddr == null) {
            throw new InvalidIPAddressException("NULL IP Address");
        }

        String[] addrArray = ipAddr.split("\\.");

        if (addrArray.length != 4) {
            throw new InvalidIPAddressException("Invalid IP Address length");
        }

        long num = 0;
        for (int i = 0; i < addrArray.length; i++) {
            int power = 3 - i;

            int octet = Integer.parseInt(addrArray[i]);

            if (octet < 0 || octet > 255) {
                throw new InvalidIPAddressException(
                        "Invalid octet, it must be between 0-255");
            }

            num += ((octet % 256) * Math.pow(256, power));
        }
        return num;
    }
}

Related Tutorials