Java Socket Address Get format(final SocketAddress s, final int defaultPort)

Here you can find the source of format(final SocketAddress s, final int defaultPort)

Description

Format an address string into host:port or *:port syntax.

License

Apache License

Declaration

public static String format(final SocketAddress s, final int defaultPort) 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.net.InetSocketAddress;
import java.net.SocketAddress;

public class Main {
    /** Format an address string into {@code host:port} or {@code *:port} syntax. */
    public static String format(final SocketAddress s, final int defaultPort) {
        if (s instanceof InetSocketAddress) {
            final InetSocketAddress addr = (InetSocketAddress) s;
            if (addr.getPort() == defaultPort) {
                return safeHostname(hostname(addr));
            }//from w  w w  . j a va 2 s . c om
            return format(hostname(addr), addr.getPort());
        }
        return s.toString();
    }

    /** Format an address string into {@code host:port} or {@code *:port} syntax. */
    public static String format(String hostname, int port) {
        return safeHostname(hostname) + ":" + port;
    }

    private static String safeHostname(String hostname) {
        if (0 <= hostname.indexOf(':')) {
            hostname = "[" + hostname + "]";
        }
        return hostname;
    }

    /** Get the name or IP address, or {@code *} if this address is a wildcard IP. */
    public static String hostname(final InetSocketAddress addr) {
        if (addr.getAddress() != null) {
            if (addr.getAddress().isAnyLocalAddress()) {
                return "*";
            }
            return addr.getAddress().getHostName();
        }
        return addr.getHostName();
    }
}

Related

  1. createInetSocketAddress(String ip, int port)
  2. describe(InetSocketAddress localAddress)
  3. encodedStringToInetSocketAddress(String str)
  4. extractClientAddress(SocketAddress remoteAddress)
  5. extractHostAddr(InetSocketAddress address)
  6. formatInetAddr(InetSocketAddress addr)
  7. formatSocketAddress(final InetSocketAddress inetSocketAddress)
  8. formatSocketAddress(SocketAddress address)
  9. get2428Address(InetSocketAddress address)