Here you can find the source of isLocalAddress(Socket socket)
Parameter | Description |
---|---|
socket | the socket |
public static boolean isLocalAddress(Socket socket) throws UnknownHostException
//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; } }