Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.net.InetAddress;

public class Main {
    /**
     * Checks validity of a dotted IP address string.
     * Uses {@link java.net.InetAddress}.getByName() method.
     *
     * @param ipStr
     * @return
     */
    public static boolean isValidIp(String ipStr) {
        try {
            InetAddress ip = InetAddress.getByName(ipStr);
            return ip2Long(ipStr) > 0;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * Transforms dotted IP address to long number.
     *
     * @param ipStr Dotted ip ie. "127.0.0.1"
     * @return Long number ie. "2130706433"
     */
    public static long ip2Long(String ipStr) {
        long result = 0;
        try {
            InetAddress ip = InetAddress.getByName(ipStr);
            byte[] octets = ip.getAddress();
            for (byte octet : octets) {
                result <<= 8;
                result |= octet & 0xff;
            }
        } catch (Exception e) {
        }
        return result;
    }
}