Here you can find the source of getLocalAddressFromNetworkInterfacesListeningOnPort(int pPort)
private static InetAddress getLocalAddressFromNetworkInterfacesListeningOnPort(int pPort)
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.*; import java.util.*; public class Main { private static Method isUp; private static InetAddress getLocalAddressFromNetworkInterfacesListeningOnPort(int pPort) { try {/*from ww w. ja v a 2 s . c o m*/ Enumeration<NetworkInterface> networkInterfaces; networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface nif = networkInterfaces.nextElement(); for (Enumeration<InetAddress> addrEnum = nif.getInetAddresses(); addrEnum.hasMoreElements();) { InetAddress interfaceAddress = addrEnum.nextElement(); if (!interfaceAddress.isLoopbackAddress() && checkMethod(nif, isUp) && isPortOpen(interfaceAddress, pPort)) { return interfaceAddress; } } } } catch (SocketException e) { return null; } return null; } private static Boolean checkMethod(NetworkInterface iface, Method toCheck) { if (toCheck != null) { try { return (Boolean) toCheck.invoke(iface, (Object[]) null); } catch (IllegalAccessException e) { return false; } catch (InvocationTargetException e) { return false; } } // Cannot check, hence we assume that is true return true; } private static boolean isPortOpen(InetAddress pAddress, int pPort) { Socket socket = null; try { socket = new Socket(); socket.setReuseAddress(true); SocketAddress sa = new InetSocketAddress(pAddress, pPort); socket.connect(sa, 200); return socket.isConnected(); } catch (IOException e) { return false; } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { // Best effort. Hate that close throws an IOException, btw. Never saw a real use case for that. } } } } }