2

Having a java.net.NetworkInterface, is it possible to know the kind of interface we're dealing with (Wi-Fi, Ethernet, etc...)?

UPDATE

BTW: I'm on a Mac, and on a mac, NetworkInterface.getDisplayName() give "en0", "en1", "lo0", etc... (same as getName())

Maurice Perry
  • 32,610
  • 9
  • 70
  • 97

1 Answers1

-1

using the code from:

How to Determine Internet Network Interface in Java

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
OUTER : for (NetworkInterface interface_ : Collections.list(interfaces)) {
  // we shouldn't care about loopback addresses
  if (interface_.isLoopback())
    continue;

  // if you don't expect the interface to be up you can skip this
  // though it would question the usability of the rest of the code
  if (!interface_.isUp())
    continue;

  // iterate over the addresses associated with the interface
  Enumeration<InetAddress> addresses = interface_.getInetAddresses();
  for (InetAddress address : Collections.list(addresses)) {
    // look only for ipv4 addresses
    if (address instanceof Inet6Address)
      continue;

    // use a timeout big enough for your needs
    if (!address.isReachable(3000))
      continue;

    // java 7's try-with-resources statement, so that
    // we close the socket immediately after use
    try (SocketChannel socket = SocketChannel.open()) {
      // again, use a big enough timeout
      socket.socket().setSoTimeout(3000);

      // bind the socket to your local interface
      socket.bind(new InetSocketAddress(address, 8080));

      // try to connect to *somewhere*
      socket.connect(new InetSocketAddress("google.com", 80));
    } catch (IOException ex) {
      ex.printStackTrace();
      continue;
    }

    System.out.format("ni: %s, ia: %s\n", interface_, address);

    // stops at the first *working* solution
    break OUTER;
  }
}
Community
  • 1
  • 1
RamonBoza
  • 8,898
  • 6
  • 36
  • 48
  • 2
    -1. Question asks "How can I tell if my interface is WiFi?" Answer suggests "Try connecting to google.com on port 80 to see if you're on the internet." – Ian McLaird Nov 13 '13 at 16:14