提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
选择默认网络接口
//package com.nowjava; import java.net.InetAddress; import java.net.NetworkInterface;/** 时 代 Java 公 众 号 - nowjava.com 提 供 **/ import java.util.Enumeration; public class Main { public static void main(String[] argv) throws Exception { System.out.println(getDefaultNetworkInterface()); } /** * Selects the default network interface * @return network interface */ public static NetworkInterface getDefaultNetworkInterface() { try { /** from nowjava - 时代Java**/ Enumeration<NetworkInterface> networks = NetworkInterface .getNetworkInterfaces(); while (networks.hasMoreElements()) { NetworkInterface ni = networks.nextElement(); Enumeration<InetAddress> addresses = ni.getInetAddresses(); boolean hasAddress = false; while (addresses.hasMoreElements()) { InetAddress ia = addresses.nextElement(); if (!(ia.isAnyLocalAddress() || ia.isLinkLocalAddress() || ia.isLoopbackAddress() || ia.isSiteLocalAddress() || ni .isPointToPoint())) {