Java Socket Address Get getRandomLoopbackInetSocketAddress(final int port)

Here you can find the source of getRandomLoopbackInetSocketAddress(final int port)

Description

get Random Loopback Inet Socket Address

License

Open Source License

Declaration

public static InetSocketAddress getRandomLoopbackInetSocketAddress(final int port) 

Method Source Code


//package com.java2s;
/*//  w w  w  .j a va  2s.  co  m
 * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

import java.net.InetSocketAddress;

public class Main {
    public static InetSocketAddress getRandomLoopbackInetSocketAddress(final int port) {
        return new InetSocketAddress(getRandomLoopbackIpAddress(), port);
    }

    public static InetSocketAddress getRandomLoopbackInetSocketAddress() {
        return getRandomLoopbackInetSocketAddress(getRandomPort());
    }

    /**
     * Generate a random loopback ip address
     * IP address range: 127.50.50.50 ~ 127.250.250.250
     * We did not utilize the whole 127./8 range to avoid using common addresses like 127.0.0.1
     * @return Generated random loopback IP address
     */
    public static String getRandomLoopbackIpAddress() {
        final StringBuilder sb = new StringBuilder("127");
        for (int i = 0; i < 3; i++) {
            sb.append(".").append(50 + (int) Math.round(Math.random() * 200));
        }
        return sb.toString();
    }

    /**
     * Generate a random high range port number
     *
     * @return A port number range from 20000 to 60000
     */
    public static int getRandomPort() {
        final int randPort = 20000 + (int) Math.round(40000 * Math.random());
        return randPort;
    }
}

Related

  1. getLocalSocketAddress(String host, int port)
  2. getNetworkVersion(InetSocketAddress address)
  3. getOffsettedAddress(InetSocketAddress isa, int offset)
  4. getPort(InetSocketAddress socket)
  5. getPort(SocketAddress socketAddress)
  6. getRawAddress(InetSocketAddress inetSocketAddress)
  7. getSimpleIpport(SocketAddress remoteAddr)
  8. getSocketAddress(InetSocketAddress socket)
  9. getSocketAddress(SocketAddress socketAddress)