Java Socket Address Get getBestAddress(InetSocketAddress addr)

Here you can find the source of getBestAddress(InetSocketAddress addr)

Description

get Best Address

License

Open Source License

Declaration

public static InetSocketAddress getBestAddress(InetSocketAddress addr) throws SocketException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.net.InetSocketAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class Main {
    public static InetSocketAddress getBestAddress(InetSocketAddress addr) throws SocketException {
        Enumeration<NetworkInterface> networkIfs = NetworkInterface.getNetworkInterfaces();
        while (networkIfs.hasMoreElements()) {
            NetworkInterface networkIf = networkIfs.nextElement();
            if (!networkIf.isLoopback() && networkIf.isUp()) {
                boolean found = false;
                for (InterfaceAddress a : networkIf.getInterfaceAddresses()) {
                    if (a.getAddress().getClass().equals(addr.getAddress().getClass())) {
                        addr = new InetSocketAddress(a.getAddress(), addr.getPort());
                        found = true;/*w  w  w.  ja  va 2  s . c  om*/
                    }
                }
                if (found) {
                    break;
                }
            }
        }
        return addr;
    }
}

Related

  1. getAddress(SocketAddress address)
  2. getAddressFirst(InetSocketAddress inetSocketAddress)
  3. getAddressRepresentation(final SocketAddress address)
  4. getAddrString(final SocketAddress address)
  5. getAlreadyBoundServerSocket(String address, int port, boolean ssl, boolean useChannels)
  6. getCanonicalConnectionAddress(InetSocketAddress address)
  7. getClientPort(SocketAddress socketAddress)
  8. getConnectAddress(InetSocketAddress addr)
  9. getConnString(SocketAddress address)