确定网络接口的类型

时间:2013-11-13 15:29:40

标签: java networking

拥有java.net.NetworkInterface,是否有可能知道我们正在处理的接口类型(Wi-Fi,以太网等)?

更新

BTW:我在Mac上,在Mac上,NetworkInterface.getDisplayName()给出“en0”,“en1”,“lo0”等...(与getName()相同)

1 个答案:

答案 0 :(得分:-1)

使用以下代码:

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;
  }
}