java.net.NetworkInterface#isLoopback ( )源码实例Demo

下面列出了java.net.NetworkInterface#isLoopback ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: WifiChat   文件: WifiUtils.java
public static String getBroadcastAddress() {
    System.setProperty("java.net.preferIPv4Stack", "true");
    try {
        for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum
                .hasMoreElements();) {
            NetworkInterface ni = niEnum.nextElement();
            if (!ni.isLoopback()) {
                for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
                    if (interfaceAddress.getBroadcast() != null) {
                        logger.d(interfaceAddress.getBroadcast().toString().substring(1));
                        return interfaceAddress.getBroadcast().toString().substring(1);
                    }
                }
            }
        }
    }
    catch (SocketException e) {
        e.printStackTrace();
    }

    return null;
}
 
源代码2 项目: j2objc   文件: DatagramChannelTest.java
private static InetAddress getNonLoopbackNetworkInterfaceAddress(boolean ipv4) throws IOException {
    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    while (networkInterfaces.hasMoreElements()) {
        NetworkInterface networkInterface = networkInterfaces.nextElement();
        if (networkInterface.isLoopback() || !networkInterface.isUp()) {
            continue;
        }
        Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
        while (inetAddresses.hasMoreElements()) {
            InetAddress inetAddress = inetAddresses.nextElement();
            if ( (ipv4 && inetAddress instanceof Inet4Address)
                    || (!ipv4 && inetAddress instanceof Inet6Address)) {
                return inetAddress;
            }
        }
    }
    return null;
}
 
源代码3 项目: samba-documents-provider   文件: BroadcastUtils.java
static List<String> getBroadcastAddress() throws BrowsingException, SocketException {
  Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

  List<String> broadcastAddresses = new ArrayList<>();

  while (interfaces.hasMoreElements()) {
    NetworkInterface networkInterface = interfaces.nextElement();
    if (networkInterface.isLoopback()) {
      continue;
    }

    for (InterfaceAddress interfaceAddress :
            networkInterface.getInterfaceAddresses()) {
      InetAddress broadcast = interfaceAddress.getBroadcast();

      if (broadcast != null) {
        broadcastAddresses.add(broadcast.toString().substring(1));
      }
    }
  }

  return broadcastAddresses;
}
 
源代码4 项目: sofa-jraft   文件: TestUtils.java
public static String getMyIp() {
    String ip = null;
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            // filters out 127.0.0.1 and inactive interfaces
            if (iface.isLoopback() || !iface.isUp()) {
                continue;
            }

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                if (addr instanceof Inet4Address) {
                    ip = addr.getHostAddress();
                    break;
                }
            }
        }
        return ip;
    } catch (SocketException e) {
        return "localhost";
    }
}
 
源代码5 项目: onos   文件: ClusterMetadataManager.java
private IpAddress findLocalIp() throws SocketException {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface iface = interfaces.nextElement();
        if (iface.isLoopback() || iface.isPointToPoint()) {
            continue;
        }

        Enumeration<InetAddress> inetAddresses = iface.getInetAddresses();
        while (inetAddresses.hasMoreElements()) {
            InetAddress inetAddress = inetAddresses.nextElement();
            if (inetAddress instanceof Inet4Address) {
                Inet4Address inet4Address = (Inet4Address) inetAddress;
                try {
                    if (!inet4Address.getHostAddress().equals(InetAddress.getLocalHost().getHostAddress())) {
                        return IpAddress.valueOf(inetAddress);
                    }
                } catch (UnknownHostException e) {
                    return IpAddress.valueOf(inetAddress);
                }
            }
        }
    }
    throw new IllegalStateException("Unable to determine local ip");
}
 
源代码6 项目: blockchain   文件: CommonUtils.java
/**
 * 判断ip地址是不是本机
 * 
 * @param host
 * @return
 */
public static boolean isLocal(String host) {
	try {
		Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
		while (allNetInterfaces.hasMoreElements()) {
			NetworkInterface netInterface = allNetInterfaces.nextElement();

			// 去除回环接口\子接口\未运行接口
			if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
				continue;
			}

			Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
			while (addresses.hasMoreElements()) {
				InetAddress ip = addresses.nextElement();
				if (ip != null) {
					if (ip.getHostAddress().equals(host))
						return true;
				}
			}
		}
	} catch (SocketException e) {
		e.printStackTrace();
	}
	return false;
}
 
源代码7 项目: dhcp4j   文件: DhcpInterfaceManager.java
@Override
public boolean apply(NetworkInterface iface) {
    try {
        if (iface == null) {
            LOG.debug("Ignoring NetworkInterface: null!");
            return false;
        }
        // Bridges claim to be down when no attached interfaces are up. :-(
        // if (false && !iface.isUp()) { LOG.debug("Ignoring NetworkInterface: Down: {}", iface); return false; }
        if (iface.isLoopback()) {
            LOG.debug("Ignoring NetworkInterface: Loopback: {}", iface);
            return false;
        }
        if (iface.isPointToPoint()) {
            LOG.debug("Ignoring NetworkInterface: PointToPoint: {}", iface);
            return false;
        }
        return true;
    } catch (SocketException e) {
        LOG.error("Failed to query " + iface, e);
        return false;
    }
}
 
源代码8 项目: hbase   文件: Addressing.java
private static InetAddress getIpAddress(AddressSelectionCondition condition) throws
    SocketException {
  // Before we connect somewhere, we cannot be sure about what we'd be bound to; however,
  // we only connect when the message where client ID is, is long constructed. Thus,
  // just use whichever IP address we can find.
  Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
  while (interfaces.hasMoreElements()) {
    NetworkInterface current = interfaces.nextElement();
    if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue;
    Enumeration<InetAddress> addresses = current.getInetAddresses();
    while (addresses.hasMoreElements()) {
      InetAddress addr = addresses.nextElement();
      if (addr.isLoopbackAddress()) continue;
      if (condition.isAcceptableAddress(addr)) {
        return addr;
      }
    }
  }

  throw new SocketException("Can't get our ip address, interfaces are: " + interfaces);
}
 
源代码9 项目: tchannel-java   文件: TChannelUtilities.java
public static int scoreAddr(@NotNull NetworkInterface iface, @NotNull InetAddress addr) {
    int score = 0;

    if (addr instanceof Inet4Address) {
        score += 300;
    }

    try {
        if (!iface.isLoopback() && !addr.isLoopbackAddress()) {
            score += 100;
            if (iface.isUp()) {
                score += 100;
            }
        }
    } catch (SocketException e) {
        logger.error("Unable to score IP {} of interface {}", addr, iface, e);
    }

    return score;
}
 
源代码10 项目: swingsane   文件: DiscoveryJob.java
public final InetAddress getLocalAddress() throws SocketException {
  for (final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces
      .hasMoreElements();) {
    final NetworkInterface networkInterface = interfaces.nextElement();
    if (networkInterface.isLoopback()) {
      continue;
    }
    for (final InterfaceAddress interfaceAddr : networkInterface.getInterfaceAddresses()) {
      final InetAddress inetAddr = interfaceAddr.getAddress();
      if (!(inetAddr instanceof Inet4Address)) {
        continue;
      }
      return inetAddr;
    }
  }
  return null;
}
 
源代码11 项目: Alice-LiveMan   文件: MediaProxyManager.java
public static String getIpAddress() {
    try {
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = allNetInterfaces.nextElement();
            if (!netInterface.isLoopback() && !netInterface.isVirtual() && netInterface.isUp()) {
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = addresses.nextElement();
                    if (ip instanceof Inet4Address) {
                        LOGGER.info("MediaProxy Server IPAddress:" + ip.getHostAddress());
                        return ip.getHostAddress();
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("IP地址获取失败", e);
    }
    return "127.0.0.1";
}
 
源代码12 项目: MaxKey   文件: EthernetAddress.java
/**
 * Factory method that locates a network interface that has
 * a suitable mac address (ethernet cards, and things that
 * emulate one), and return that address. If there are multiple
 * applicable interfaces, one of them is returned; which one
 * is returned is not specified.
 * Method is meant for accessing an address needed to construct
 * generator for time+location based UUID generation method.
 * 
 * @return Ethernet address of one of interfaces system has;
 *    not including local or loopback addresses; if one exists,
 *    null if no such interfaces are found.
 */
public static EthernetAddress fromInterface()
{
    try {
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface nint = en.nextElement();
            if (!nint.isLoopback()) {
                byte[] data = nint.getHardwareAddress();
                if (data != null && data.length == 6) {
                    return new EthernetAddress(data);
                }
            }
        }
    } catch (java.net.SocketException e) {
        // fine, let's take is as signal of not having any interfaces
    }
    return null;
}
 
源代码13 项目: myMediaCodecPlayer-for-FPV   文件: TestActivity.java
public void printLocalIpAddresses(){
    String s="";
    try{
        for(Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){
            NetworkInterface intf=en.nextElement();
            for(Enumeration<InetAddress> enumIpAddr=intf.getInetAddresses();enumIpAddr.hasMoreElements();){
                InetAddress inetAddress=enumIpAddr.nextElement();
                if(!intf.isLoopback()){
                    s+="Interface "+intf.getName()+": "+inetAddress.getHostAddress()+"\n";
                }
            }
        }
        makeText(s,mTextView3);
    }catch(Exception e){e.printStackTrace();}
}
 
源代码14 项目: bt   文件: AddressUtils.java
public static boolean isValidBindAddress(InetAddress addr) {
	// we don't like them them but have to allow them
	if(addr.isAnyLocalAddress())
		return true;
	try {
		NetworkInterface iface = NetworkInterface.getByInetAddress(addr);
		if(iface == null)
			return false;
		return iface.isUp() && !iface.isLoopback();
	} catch (SocketException e) {
		return false;
	}
}
 
源代码15 项目: openhab1-addons   文件: LocalNetworkInterface.java
/**
 * Finds the (non loopback, non localhost) local network interface to be
 * connected to from other machines.
 *
 * @return
 */
public static String getLocalNetworkInterface() {
    String localInterface = null;
    Enumeration<NetworkInterface> interfaces = null;
    try {
        interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual()) {
                continue;
            }
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress current_addr = addresses.nextElement();
                if (current_addr.isLoopbackAddress() || (current_addr instanceof Inet6Address)) {
                    continue;
                }
                if (localInterface != null) {
                    logger.warn("Found multiple local interfaces! Replacing " + localInterface + " with "
                            + current_addr.getHostAddress());
                }
                localInterface = current_addr.getHostAddress();
            }
        }
    } catch (SocketException e) {
        logger.error("Could not retrieve network interface. ", e);
        return null;
    }
    return localInterface;
}
 
源代码16 项目: smarthome   文件: NetUtil.java
/**
 * @deprecated Please use the NetworkAddressService with {@link #getPrimaryIpv4HostAddress()}
 *
 *             Get the first candidate for a local IPv4 host address (non loopback, non localhost).
 */
@Deprecated
public static @Nullable String getLocalIpv4HostAddress() {
    try {
        String hostAddress = null;
        final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            final NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual() || current.isPointToPoint()) {
                continue;
            }
            final Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                final InetAddress currentAddr = addresses.nextElement();
                if (currentAddr.isLoopbackAddress() || (currentAddr instanceof Inet6Address)) {
                    continue;
                }
                if (hostAddress != null) {
                    LOGGER.warn("Found multiple local interfaces - ignoring {}", currentAddr.getHostAddress());
                } else {
                    hostAddress = currentAddr.getHostAddress();
                }
            }
        }
        return hostAddress;
    } catch (SocketException ex) {
        LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex);
        return null;
    }
}
 
源代码17 项目: AndroidUtilCode   文件: NetworkUtils.java
/**
 * Return the ip address.
 * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p>
 *
 * @param useIPv4 True to use ipv4, false otherwise.
 * @return the ip address
 */
@RequiresPermission(INTERNET)
public static String getIPAddress(final boolean useIPv4) {
    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        LinkedList<InetAddress> adds = new LinkedList<>();
        while (nis.hasMoreElements()) {
            NetworkInterface ni = nis.nextElement();
            // To prevent phone of xiaomi return "10.0.2.15"
            if (!ni.isUp() || ni.isLoopback()) continue;
            Enumeration<InetAddress> addresses = ni.getInetAddresses();
            while (addresses.hasMoreElements()) {
                adds.addFirst(addresses.nextElement());
            }
        }
        for (InetAddress add : adds) {
            if (!add.isLoopbackAddress()) {
                String hostAddress = add.getHostAddress();
                boolean isIPv4 = hostAddress.indexOf(':') < 0;
                if (useIPv4) {
                    if (isIPv4) return hostAddress;
                } else {
                    if (!isIPv4) {
                        int index = hostAddress.indexOf('%');
                        return index < 0
                                ? hostAddress.toUpperCase()
                                : hostAddress.substring(0, index).toUpperCase();
                    }
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return "";
}
 
源代码18 项目: ByteJTA   文件: XidFactoryImpl.java
private static byte[] getHardwareAddress() {
	Enumeration<NetworkInterface> enumeration = null;
	try {
		enumeration = NetworkInterface.getNetworkInterfaces();
	} catch (Exception ex) {
		logger.debug(ex.getMessage(), ex);
	}

	byte[] byteArray = null;
	while (byteArray == null && enumeration != null && enumeration.hasMoreElements()) {
		NetworkInterface element = enumeration.nextElement();

		try {
			if (element.isUp() == false) {
				continue;
			} else if (element.isPointToPoint() || element.isVirtual()) {
				continue;
			} else if (element.isLoopback()) {
				continue;
			}

			byte[] hardwareAddr = element.getHardwareAddress();
			if (hardwareAddr == null || hardwareAddr.length != SIZE_OF_MAC) {
				continue;
			}

			byteArray = new byte[SIZE_OF_MAC];
			System.arraycopy(hardwareAddr, 0, byteArray, 0, SIZE_OF_MAC);
		} catch (Exception rex) {
			logger.debug(rex.getMessage(), rex);
		}
	}

	return byteArray != null ? byteArray : new byte[SIZE_OF_MAC];
}
 
源代码19 项目: scheduling   文件: BroadcastDiscoveryClient.java
private boolean isLoopBack(NetworkInterface networkInterface) {
    try {
        return networkInterface.isLoopback() || !networkInterface.isUp();
    } catch (SocketException e) {
        return false;
    }
}
 
源代码20 项目: mldht   文件: AddressUtils.java
public static boolean isValidBindAddress(InetAddress addr) {
	// we don't like them them but have to allow them
	if(addr.isAnyLocalAddress())
		return true;
	try {
		NetworkInterface iface = NetworkInterface.getByInetAddress(addr);
		if(iface == null)
			return false;
		return iface.isUp() && !iface.isLoopback();
	} catch (SocketException e) {
		return false;
	}
}