-1

How can I know, which interface will allow UPD connection? I get the list of all network interfaces like this:

Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();

$ ipconfig
Windows IP Configuration

Ethernet adapter Local Area Connection:

   Connection-specific DNS Suffix  . : myworld.com
   IPv4 Address. . . . . . . . . . . : 10.219.1.157
   Subnet Mask . . . . . . . . . . . : 255.255.254.0
   Default Gateway . . . . . . . . . : 10.219.0.1

Tunnel adapter isatap.myworld.com:
   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : myworld.com
impossible
  • 2,380
  • 8
  • 36
  • 60
  • Possible duplicate of [TCP/IP connection on a specific interface](https://stackoverflow.com/questions/14697963/tcp-ip-connection-on-a-specific-interface) – Oliver Feb 04 '19 at 08:41
  • Hi Oliver, this is not a duplicate question. Since windows based ipconfig doesn't provide detailed information, like listing all interfaces, type of connections supported etc. Hence, I had to iterate over all the interfaces to test my UDP connection. – impossible Feb 04 '19 at 09:34

1 Answers1

1

The solution I found is to iterate over all the interfaces, and test which is enabled for connection: Sample working code is:

public static DatagramChannel openDatagramChannelForAnyWorkingInterface(int port, String ip) throws IOException {

    DatagramChannel channel;
    try {
        channel = DatagramChannel.open(StandardProtocolFamily.INET);
        channel.configureBlocking(true);
        channel.socket().setReuseAddress(true);
        channel.bind(new InetSocketAddress(port));
        Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface np : Collections.list(networkInterfaceEnumeration)) {
            try {
                channel.join(InetAddress.getByName(ip), NetworkInterface.getByName(np.getName()));
                log.info("Data joining channel ip [{}], port [{}] interface [{}]", ip, port, np.getName());
                break;
            } catch (Exception ignore) {
            }
        }
    } catch (Exception e) {
        log.error("Exception while subscribing to market data: ", e);
        throw e;
    }
    return channel;
}
impossible
  • 2,380
  • 8
  • 36
  • 60