Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.net.InetAddress;

import java.util.Random;

public class Main {
    /**
     * Returns a valid IP v4 address.
     *
     * @return [0-255].[0-255].[0-255].[0-255]
     */
    public static String generateRandomIp() {
        try {
            Random r = new Random();
            String ip = r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
            if (isValidIp(ip)) {
                return ip;
            } else {
                return generateRandomIp();
            }
        } catch (Exception e) {
        }
        return "127.0.0.1";
    }

    /**
     * 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;
    }
}