下面列出了java.net.NetworkInterface#getDisplayName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static NetworkData buildNetworkData(NetworkInterface networkInterface, InetAddress inetAddress)
throws SocketException {
if (isPhysicalNetworkInterface(networkInterface)) {
String hostName = inetAddress != null ? inetAddress.getHostName() : null;
String hostCanonicalName = inetAddress != null ? inetAddress.getCanonicalHostName() : null;
String interfaceName = networkInterface.getName();
String interfaceDisplayName = networkInterface.getDisplayName();
String interfaceHardwareAddress = ByteUtil.toHexadecimal(networkInterface.getHardwareAddress());
List<String> interfaceAddresses = getInterfaceAddresses(networkInterface);
NetworkData networkData = new NetworkData();
networkData.setHostName(hostName);
networkData.setHostCanonicalName(hostCanonicalName);
networkData.setInterfaceName(interfaceName);
networkData.setInterfaceDisplayName(interfaceDisplayName);
networkData.setInterfaceHardwareAddress(interfaceHardwareAddress);
networkData.setInterfaceAddresses(interfaceAddresses);
return networkData;
}
return null;
}
/**
* 获取本机ipv4地址列表
* @return
*/
public static List<String> getLocalV4IPs(){
List<String> ips = new ArrayList<String>();
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while(interfaces.hasMoreElements()){
NetworkInterface ni = interfaces.nextElement();
String name = ni.getDisplayName();
if(!ni.isLoopback()&&!ni.isVirtual()&&ni.isUp()){
if(name==null||!name.contains("Loopback")){
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while(addresses.hasMoreElements()){
InetAddress address = addresses.nextElement();
String ip = address.getHostAddress();
if(!ip.contains(":")){
ips.add(ip);
}
}
}
}
}
} catch (SocketException e) {
logger.error("localips error",e);
}
return ips;
}
public static String resolveHostIP(String netInterface) {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.getDisplayName().startsWith(netInterface)) {
Enumeration<InetAddress> ips = networkInterface.getInetAddresses();
while (ips.hasMoreElements()) {
InetAddress inetAddress = ips.nextElement();
if (inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
return networkInterface.getDisplayName();
}
}
return InetAddress.getLocalHost().getHostAddress();
} catch (Exception e) {
return "127.0.0.1";
}
}
/**
* Retruns the inductor IP address (IPV4 address). If there are multiple NICs/IfAddresses, it
* selects the first one. Openstack VMs normally has only one network interface (eth0).
*
* @return IPV4 address of inductor with interface name. Returns <code>null</code> if it couldn't
* find anything.
*/
private String getInductorIPv4Addr() {
try {
Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
while (nics.hasMoreElements()) {
NetworkInterface nic = nics.nextElement();
if (nic.isUp() && !nic.isLoopback()) {
Enumeration<InetAddress> addrs = nic.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress add = addrs.nextElement();
// Print only IPV4 address
if (add instanceof Inet4Address && !add.isLoopbackAddress()) {
// Log the first one.
String ip = add.getHostAddress() + " (" + nic.getDisplayName() + ")";
logger.info("Inductor IP : " + ip);
return ip;
}
}
}
}
} catch (Exception e) {
logger.warn("Error getting inductor IP address", e);
// Skip any errors
}
return null;
}
static void testAllNetworkInterfaces() throws Exception {
System.err.println("\n testAllNetworkInterfaces: \n ");
for (Enumeration<NetworkInterface> e = NetworkInterface
.getNetworkInterfaces(); e.hasMoreElements();) {
NetworkInterface netIF = e.nextElement();
// Skip (Windows)Teredo Tunneling Pseudo-Interface
if (isWindows) {
String dName = netIF.getDisplayName();
if (dName != null && dName.contains("Teredo")) {
continue;
}
}
for (Enumeration<InetAddress> iadrs = netIF.getInetAddresses(); iadrs
.hasMoreElements();) {
InetAddress iadr = iadrs.nextElement();
if (iadr instanceof Inet6Address) {
System.err.println("Test NetworkInterface: " + netIF);
Inet6Address i6adr = (Inet6Address) iadr;
System.err.println("Testing with " + iadr);
System.err.println(" scoped iface: "
+ i6adr.getScopedInterface());
testInet6AddressSerialization(i6adr, null);
}
}
}
}
public Value getNetworkInterfaceNames()
throws FaultException {
Value response = Value.create();
ValueVector interfaces = response.getChildren( "interfaceName" );
try {
Enumeration< NetworkInterface > list = NetworkInterface.getNetworkInterfaces();
int index = 0;
while( list.hasMoreElements() ) {
NetworkInterface n = list.nextElement();
interfaces.get( index ).setValue( n.getName() );
if( n.getDisplayName() == null ) {
interfaces.get( index ).getFirstChild( "displayName" ).setValue( "" );
} else {
interfaces.get( index ).getFirstChild( "displayName" ).setValue( n.getDisplayName() );
}
index++;
}
} catch( SocketException e ) {
throw new FaultException( e );
}
return response;
}
public InetAddress getLocalAddress(NetworkInterface networkInterface, boolean isIPv6, InetAddress remoteAddress) {
// First try to find a local IP that is in the same subnet as the remote IP
InetAddress localIPInSubnet = getBindAddressInSubnetOf(remoteAddress);
if (localIPInSubnet != null) return localIPInSubnet;
// There are two reasons why we end up here:
//
// - Windows Vista returns a 64 or 128 CIDR prefix if you ask it for the network prefix length of an IPv4 address!
//
// - We are dealing with genuine IPv6 addresses
//
// - Something is really wrong on the LAN and we received a multicast datagram from a source we can't reach via IP
log.finer("Could not find local bind address in same subnet as: " + remoteAddress.getHostAddress());
// Next, just take the given interface (which is really totally random) and get the first address that we like
for (InetAddress interfaceAddress: getInetAddresses(networkInterface)) {
if (isIPv6 && interfaceAddress instanceof Inet6Address)
return interfaceAddress;
if (!isIPv6 && interfaceAddress instanceof Inet4Address)
return interfaceAddress;
}
throw new IllegalStateException("Can't find any IPv4 or IPv6 address on interface: " + networkInterface.getDisplayName());
}
public static Map<String, String> getMyIPv4Addresses() {
Map<String, String> networkList = new HashMap<>();
try {
Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface networkInterface = (NetworkInterface) enumeration.nextElement();
Enumeration ee = networkInterface.getInetAddresses();
while (ee.hasMoreElements()) {
InetAddress ip = (InetAddress) ee.nextElement();
Pattern IPV4_PATTERN = Pattern.compile(IPV4_REGEX);
// if it is IPv4 Address
if (IPV4_PATTERN.matcher(ip.getHostAddress()).matches()) {
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
if (mac != null) {
StringBuilder macBuilder = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
macBuilder.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
}
String name = networkInterface.getDisplayName();
String ipv4 = ip.getHostAddress();
networkList.put(name, ipv4);
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return networkList;
}
NetworkInformation() {
networkList = new ArrayList<>();
try {
Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface networkInterface = (NetworkInterface) enumeration.nextElement();
Enumeration ee = networkInterface.getInetAddresses();
while (ee.hasMoreElements()) {
InetAddress ip = (InetAddress) ee.nextElement();
Pattern IPV4_PATTERN = Pattern.compile(IPV4_REGEX);
// if it is IPv4 Address
if (IPV4_PATTERN.matcher(ip.getHostAddress()).matches()) {
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
String macAddress;
if (mac != null) {
StringBuilder macBuilder = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
macBuilder.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
macAddress = macBuilder.toString();
} else {
macAddress = "Undefined";
}
String ipAddress = ip.getHostAddress();
String name = networkInterface.getDisplayName();
networkList.add(new Network(ipAddress, macAddress, name));
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
private static boolean isNotExcludedInterface(NetworkInterface nif) {
if (Platform.isOSX() && nif.getName().contains("awdl")) {
return false;
}
String dName = nif.getDisplayName();
if (Platform.isWindows() && dName != null && dName.contains("Teredo")) {
return false;
}
return true;
}
@Override
public InetAddress getLocalAddress(NetworkInterface networkInterface, boolean isIPv6, InetAddress remoteAddress) {
// TODO: This is totally random because we can't access low level InterfaceAddress on Android!
for (InetAddress localAddress : getInetAddresses(networkInterface)) {
if (isIPv6 && localAddress instanceof Inet6Address)
return localAddress;
if (!isIPv6 && localAddress instanceof Inet4Address)
return localAddress;
}
throw new IllegalStateException("Can't find any IPv4 or IPv6 address on interface: " + networkInterface.getDisplayName());
}
public static String getLocalIPAddress(Context context){
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
if(ipAddress == 0){
try {
Enumeration<NetworkInterface> enumerationNi = NetworkInterface.getNetworkInterfaces();
while (enumerationNi.hasMoreElements()) {
NetworkInterface networkInterface = enumerationNi.nextElement();
String interfaceName = networkInterface.getDisplayName();
if (interfaceName.equals("eth0") || interfaceName.equals("wlan0")) {
Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses();
while (enumIpAddr.hasMoreElements()) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
}
} catch (SocketException e) {
Log.e(IMEService.TAG, "获取本地IP出错", e);
}
}else {
return String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
}
return "0.0.0.0";
}
private static boolean isNotExcludedInterface(NetworkInterface nif) {
if (Platform.isOSX() && nif.getName().contains("awdl")) {
return false;
}
String dName = nif.getDisplayName();
if (Platform.isWindows() && dName != null && dName.contains("Teredo")) {
return false;
}
return true;
}
/**
* Check if the input network interface should be included in the test. It is necessary to exclude
* "Teredo Tunneling Pseudo-Interface" whose configuration can be variable during a test run.
*
* @param ni a network interace
* @return false if it is a "Teredo Tunneling Pseudo-Interface", otherwise true.
*/
private boolean isIncluded(NetworkInterface ni) {
if (!IS_WINDOWS) {
return true;
}
String dName = ni.getDisplayName();
return dName == null || !dName.contains("Teredo");
}
private static boolean isNotExcludedInterface(NetworkInterface nif) {
if (isMacOS && nif.getName().contains("awdl"))
return false;
String dName = nif.getDisplayName();
if (isWindows && dName != null && dName.contains("Teredo"))
return false;
return true;
}
public static String getDefaultNetworkInterface() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
String fallBackName = null;
while (networkInterfaces.hasMoreElements()) {
NetworkInterface nextElement = networkInterfaces.nextElement();
String name = nextElement.getDisplayName();
LOG.info("Iterating over network interfaces, found '{}'", name);
boolean hasInet = Collections.list(nextElement.getInetAddresses()).size() > 1; // Checking that inet exists, to avoid taking iBridge
if (hasInet && fallBackName == null) {
fallBackName = name;
}
if ((name.startsWith(MAC_TSO_NET_IFACE_PREFIX) && hasInet ) ||
name.startsWith(LINUX_TSO_NET_IFACE_PREFIX)) {
return name;
}
}
if (fallBackName != null) {
return fallBackName;
}
} catch (SocketException ignored) {
throw new RuntimeException("Failed to find any network interfaces", ignored);
}
throw new IllegalArgumentException(String.format("No network '%s*'/'%s*' interfaces found",
MAC_TSO_NET_IFACE_PREFIX, LINUX_TSO_NET_IFACE_PREFIX));
}
private static Map<String, List<InetAddress>> init() {
Map<String, List<InetAddress>> interfacesIpAddressesMap = new HashMap<>();
Enumeration networkInterfaces = null;
try {
networkInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException ex) {
throw new RuntimeException("Failed to get network interfaces", ex);
}
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();
networkInterface.getDisplayName();
List<InetAddress> ipAddresses = new ArrayList<>();
Enumeration ee = networkInterface.getInetAddresses();
while (ee.hasMoreElements()) {
InetAddress inetAddress = (InetAddress) ee.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ipAddresses.add(inetAddress);
}
}
interfacesIpAddressesMap.put(networkInterface.getDisplayName(), Collections.unmodifiableList(ipAddresses));
}
return Collections.unmodifiableMap(interfacesIpAddressesMap);
}
/**
* Creates a warning message about no buffer space available.
*
* @param exceptionMessage the message from <code>IOException.getMessage()</code>.
* @param intf the interface this happened to
* @param inetAddress the inet address it happened to.
* @return a new warning message about no buffer space available.
*/
private String createIgnoredWarning(final String exceptionMessage, final NetworkInterface intf,
final InetAddress inetAddress) {
return exceptionMessage + ": "
+ "interface: " + inetAddress + ", "
+ "network interface: " + intf.getDisplayName() + ", "
+ "total messages sent: " + sentMessages;
}
/**
* Validation of every discovered network interface.
* <p>
* Override this method to customize which network interfaces are used.
* </p>
* <p>
* The given implementation ignores interfaces which are
* </p>
* <ul>
* <li>loopback (yes, we do not bind to lo0)</li>
* <li>down</li>
* <li>have no bound IP addresses</li>
* <li>named "vmnet*" (OS X VMWare does not properly stop interfaces when it quits)</li>
* <li>named "vnic*" (OS X Parallels interfaces should be ignored as well)</li>
* <li>named "*virtual*" (VirtualBox interfaces, for example</li>
* <li>named "ppp*"</li>
* </ul>
*
* @param iface The interface to validate.
* @return True if the given interface matches all validation criteria.
* @throws Exception If any validation test failed with an un-recoverable error.
*/
protected boolean isUsableNetworkInterface(NetworkInterface iface) throws Exception {
if (!iface.isUp()) {
log.finer("Skipping network interface (down): " + iface.getDisplayName());
return false;
}
if (getInetAddresses(iface).size() == 0) {
log.finer("Skipping network interface without bound IP addresses: " + iface.getDisplayName());
return false;
}
if (iface.getName().toLowerCase(Locale.ENGLISH).startsWith("vmnet") ||
(iface.getDisplayName() != null && iface.getDisplayName().toLowerCase(Locale.ENGLISH).contains("vmnet"))) {
log.finer("Skipping network interface (VMWare): " + iface.getDisplayName());
return false;
}
if (iface.getName().toLowerCase(Locale.ENGLISH).startsWith("vnic")) {
log.finer("Skipping network interface (Parallels): " + iface.getDisplayName());
return false;
}
if (iface.getName().toLowerCase(Locale.ENGLISH).contains("virtual")) {
log.finer("Skipping network interface (named '*virtual*'): " + iface.getDisplayName());
return false;
}
if (iface.getName().toLowerCase(Locale.ENGLISH).startsWith("ppp")) {
log.finer("Skipping network interface (PPP): " + iface.getDisplayName());
return false;
}
if (iface.isLoopback()) {
log.finer("Skipping network interface (ignoring loopback): " + iface.getDisplayName());
return false;
}
if (useInterfaces.size() > 0 && !useInterfaces.contains(iface.getName())) {
log.finer("Skipping unwanted network interface (-D" + SYSTEM_PROPERTY_NET_IFACES + "): " + iface.getName());
return false;
}
if (!iface.supportsMulticast())
log.warning("Network interface may not be multicast capable: " + iface.getDisplayName());
return true;
}
/**
* Validation of every discovered network interface.
* <p>
* Override this method to customize which network interfaces are used.
* </p>
* <p>
* The given implementation ignores interfaces which are
* </p>
* <ul>
* <li>loopback (yes, we do not bind to lo0)</li>
* <li>down</li>
* <li>have no bound IP addresses</li>
* <li>named "vmnet*" (OS X VMWare does not properly stop interfaces when it quits)</li>
* <li>named "vnic*" (OS X Parallels interfaces should be ignored as well)</li>
* <li>named "*virtual*" (VirtualBox interfaces, for example</li>
* <li>named "ppp*"</li>
* </ul>
*
* @param iface The interface to validate.
* @return True if the given interface matches all validation criteria.
* @throws Exception If any validation test failed with an un-recoverable error.
*/
protected boolean isUsableNetworkInterface(NetworkInterface iface) throws Exception {
if (!iface.isUp()) {
log.finer("Skipping network interface (down): " + iface.getDisplayName());
return false;
}
if (getInetAddresses(iface).size() == 0) {
log.finer("Skipping network interface without bound IP addresses: " + iface.getDisplayName());
return false;
}
if (iface.getName().toLowerCase(Locale.ENGLISH).startsWith("vmnet") ||
(iface.getDisplayName() != null && iface.getDisplayName().toLowerCase(Locale.ENGLISH).contains("vmnet"))) {
log.finer("Skipping network interface (VMWare): " + iface.getDisplayName());
return false;
}
if (iface.getName().toLowerCase(Locale.ENGLISH).startsWith("vnic")) {
log.finer("Skipping network interface (Parallels): " + iface.getDisplayName());
return false;
}
if (iface.getName().toLowerCase(Locale.ENGLISH).contains("virtual")) {
log.finer("Skipping network interface (named '*virtual*'): " + iface.getDisplayName());
return false;
}
if (iface.getName().toLowerCase(Locale.ENGLISH).startsWith("ppp")) {
log.finer("Skipping network interface (PPP): " + iface.getDisplayName());
return false;
}
if (iface.isLoopback()) {
log.finer("Skipping network interface (ignoring loopback): " + iface.getDisplayName());
return false;
}
if (useInterfaces.size() > 0 && !useInterfaces.contains(iface.getName())) {
log.finer("Skipping unwanted network interface (-D" + SYSTEM_PROPERTY_NET_IFACES + "): " + iface.getName());
return false;
}
if (!iface.supportsMulticast())
log.warning("Network interface may not be multicast capable: " + iface.getDisplayName());
return true;
}