Java Code Examples for java.net.NetworkInterface#isLoopback()

The following examples show how to use java.net.NetworkInterface#isLoopback() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WifiUtils.java    From WifiChat with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: EthernetAddress.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Source File: MediaProxyManager.java    From Alice-LiveMan with GNU Affero General Public License v3.0 6 votes vote down vote up
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";
}
 
Example 4
Source File: DiscoveryJob.java    From swingsane with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: TChannelUtilities.java    From tchannel-java with MIT License 6 votes vote down vote up
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;
}
 
Example 6
Source File: Addressing.java    From hbase with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 7
Source File: DhcpInterfaceManager.java    From dhcp4j with Apache License 2.0 6 votes vote down vote up
@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;
    }
}
 
Example 8
Source File: CommonUtils.java    From blockchain with MIT License 6 votes vote down vote up
/**
 * 判断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;
}
 
Example 9
Source File: ClusterMetadataManager.java    From onos with Apache License 2.0 6 votes vote down vote up
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");
}
 
Example 10
Source File: TestUtils.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
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";
    }
}
 
Example 11
Source File: BroadcastUtils.java    From samba-documents-provider with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example 12
Source File: DatagramChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 13
Source File: NetUtil.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @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;
    }
}
 
Example 14
Source File: NetworkUtils.java    From AndroidUtilCode with Apache License 2.0 5 votes vote down vote up
/**
 * 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 "";
}
 
Example 15
Source File: XidFactoryImpl.java    From ByteJTA with GNU Lesser General Public License v3.0 5 votes vote down vote up
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];
}
 
Example 16
Source File: BroadcastDiscoveryClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean isLoopBack(NetworkInterface networkInterface) {
    try {
        return networkInterface.isLoopback() || !networkInterface.isUp();
    } catch (SocketException e) {
        return false;
    }
}
 
Example 17
Source File: LocalNetworkInterface.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 18
Source File: AddressUtils.java    From mldht with Mozilla Public License 2.0 5 votes vote down vote up
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;
	}
}
 
Example 19
Source File: AddressUtils.java    From bt with Apache License 2.0 5 votes vote down vote up
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;
	}
}
 
Example 20
Source File: TestActivity.java    From myMediaCodecPlayer-for-FPV with MIT License 5 votes vote down vote up
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();}
}