Here you can find the source of getNetworkInterfaceForRemoteIPAddress( InetAddress remoteAddress)
public static NetworkInterface getNetworkInterfaceForRemoteIPAddress( InetAddress remoteAddress) throws SocketException
//package com.java2s; /*/* w w w.j a v a2 s . co m*/ * Copyright 2015 The OpenDCT Authors. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.net.*; import java.util.Enumeration; public class Main { public static NetworkInterface getNetworkInterfaceForRemoteIPAddress( InetAddress remoteAddress) throws SocketException { byte remoteAddressBytes[] = remoteAddress.getAddress(); Enumeration<NetworkInterface> networkInterfaces = NetworkInterface .getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface currentInterface = networkInterfaces .nextElement(); // Never try to match a loopback interface. if (currentInterface.isLoopback()) { continue; } for (InterfaceAddress address : currentInterface .getInterfaceAddresses()) { byte localIPAddress[] = address.getAddress().getAddress(); // Make sure these are the same kind of IP addresses. This should only differ if one of // the addresses is v4 and the other is v6. if (localIPAddress.length != remoteAddressBytes.length) { continue; } byte localSubnet[] = new byte[localIPAddress.length]; int localSubnetLength = address.getNetworkPrefixLength(); boolean match = true; int bits = localSubnetLength; for (int i = 0; i < localSubnet.length; i++) { if (bits < 8) { localSubnet[i] = (byte) ~((1 << 8 - bits) - 1); byte localAnd = (byte) (localIPAddress[i] & localSubnet[i]); byte remoteAnd = (byte) (remoteAddressBytes[i] & localSubnet[i]); if (localAnd != remoteAnd) { match = false; break; } } else if (!(localIPAddress[i] == remoteAddressBytes[i])) { match = false; break; } bits -= 8; } if (!match) { continue; } return currentInterface; } } return null; } }