Java Socket Address Get isLocalAddress(Socket socket)

Here you can find the source of isLocalAddress(Socket socket)

Description

Check if a socket is connected to a local address.

License

Mozilla Public License

Parameter

Parameter Description
socket the socket

Return

true if it is

Declaration

public static boolean isLocalAddress(Socket socket) throws UnknownHostException 

Method Source Code

//package com.java2s;
/*//from w  ww.j a  v a2  s.  c  o  m
 * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
 * and the EPL 1.0 (http://h2database.com/html/license.html).
 * Initial Developer: H2 Group
 */

import java.net.Inet6Address;
import java.net.InetAddress;

import java.net.Socket;
import java.net.UnknownHostException;

public class Main {
    /**
     * Check if a socket is connected to a local address.
     *
     * @param socket the socket
     * @return true if it is
     */
    public static boolean isLocalAddress(Socket socket) throws UnknownHostException {
        InetAddress test = socket.getInetAddress();
        if (test.isLoopbackAddress()) {
            return true;
        }
        InetAddress localhost = InetAddress.getLocalHost();
        // localhost.getCanonicalHostName() is very very slow
        String host = localhost.getHostAddress();
        for (InetAddress addr : InetAddress.getAllByName(host)) {
            if (test.equals(addr)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Get the host address. This method adds '[' and ']' if required for
     * Inet6Address that contain a ':'.
     *
     * @param address the address
     * @return the host address
     */
    private static String getHostAddress(InetAddress address) {
        String host = address.getHostAddress();
        if (address instanceof Inet6Address) {
            if (host.indexOf(':') >= 0 && !host.startsWith("[")) {
                host = "[" + host + "]";
            }
        }
        return host;
    }
}

Related

  1. inetAddrToHoman(final InetSocketAddress sockAddr)
  2. inetSocketAddress2IpPort(InetSocketAddress addr)
  3. IpToString(InetSocketAddress address)
  4. isAddressDefined(InetSocketAddress address)
  5. isLegalPeerAddress(@CheckForNull SocketAddress socketAddress)
  6. isSameAddress(SocketAddress a1, SocketAddress a2)
  7. isUdpPortAvailable(InetSocketAddress localAddress)
  8. isUnresolved(SocketAddress address)
  9. isValidMulticastAddress(final InetSocketAddress address)