Here you can find the source of getBestAddress(InetSocketAddress addr)
public static InetSocketAddress getBestAddress(InetSocketAddress addr) throws SocketException
//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; } }