/** * A list of the non-loopback, non-link-local IP addresses of the host, or null if none found. * * @return The non-loopback, non-link-local IP addresses on the host. */ public static List<InetAddress> hostAddresses() { List<InetAddress> addrList = new ArrayList<>(); Enumeration<NetworkInterface> IFCs = null; try { IFCs = NetworkInterface.getNetworkInterfaces(); } catch (SocketException ex) { log.error("Unable to get network interfaces.", ex); } if (IFCs != null) { while (IFCs.hasMoreElements()) { NetworkInterface IFC = IFCs.nextElement(); try { if (IFC.isUp()) { Enumeration<InetAddress> addresses = IFC.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (!address.isLoopbackAddress() && !address.isLinkLocalAddress()) { addrList.add(address); } } } } catch (SocketException ex) { log.error("Unable to read network interface {}.", IFC.toString(), ex); } } } return addrList; }
public static boolean isPlatformHost(String host) { Object[] domains = getPlatformHosts().toArray(); host = host.toLowerCase(); for (int i = 0; i < domains.length; i++) { String domain = (String) domains[i]; if (domain.equals(host)) { return (true); } if (host.endsWith("." + domain)) { return (true); } } if (Constants.isCVSVersion()) { // allow local addresses for testing try { InetAddress ia = InetAddress.getByName(host); return (ia.isLoopbackAddress() || ia.isLinkLocalAddress() || ia.isSiteLocalAddress()); } catch (Throwable e) { } } return (false); }
public static Set<String> getIpAddresses() { if (_ipAddresses == null) { _ipAddresses = new HashSet<String>(); try { List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface networkInterface : networkInterfaces) { List<InetAddress> inetAddresses = Collections.list(networkInterface.getInetAddresses()); for (InetAddress inetAddress : inetAddresses) { if (inetAddress.isLinkLocalAddress() || inetAddress.isLoopbackAddress() || !(inetAddress instanceof Inet4Address)) { continue; } _ipAddresses.add(inetAddress.getHostAddress()); } } } catch (Exception e) { _log.error("Unable to read local server's IP addresses"); _log.error(e, e); } } return new HashSet<String>(_ipAddresses); }
public static String[] getNetworkParams(NetworkInterface nic) { List<InterfaceAddress> addrs = nic.getInterfaceAddresses(); if (addrs == null || addrs.size() == 0) { return null; } InterfaceAddress addr = null; for (InterfaceAddress iaddr : addrs) { InetAddress inet = iaddr.getAddress(); if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress() && inet.getAddress().length == 4) { addr = iaddr; break; } } if (addr == null) { return null; } String[] result = new String[3]; result[0] = addr.getAddress().getHostAddress(); try { byte[] mac = nic.getHardwareAddress(); result[1] = byte2Mac(mac); } catch (Exception e) { } result[2] = prefix2Netmask(addr.getNetworkPrefixLength()); return result; }
public static String getLocalIpAddress() { String IP = null; StringBuilder IPStringBuilder = new StringBuilder(); try { Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces(); while (networkInterfaceEnumeration.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement(); Enumeration<InetAddress> inetAddressEnumeration = networkInterface.getInetAddresses(); while (inetAddressEnumeration.hasMoreElements()) { InetAddress inetAddress = inetAddressEnumeration.nextElement(); if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) { IPStringBuilder.append(inetAddress.getHostAddress().toString() + "\n"); } } } } catch (SocketException ex) { } IP = IPStringBuilder.toString(); return IP; }
// on linux system public void init2() { try { NetworkInterface networkInterface = NetworkInterface.getByName("eth0"); Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress address = inetAddresses.nextElement(); if (!address.isLinkLocalAddress()) { // just get IPv4 address localAddress = address; } } // get broadcast address List<InterfaceAddress> addresses = networkInterface.getInterfaceAddresses(); for (InterfaceAddress address : addresses) { if (address.getBroadcast() != null) { broadcastAddress = address.getBroadcast(); break; } } if (broadcastAddress == null) { System.out.println("get broadcast address error!"); } System.out.println("local ip address is " + localAddress.getHostAddress()); System.out.println("broadcast address is " + broadcastAddress.getHostAddress()); socket = new DatagramSocket(); socket.setBroadcast(true); } catch (SocketException se) { se.printStackTrace(); } }
private static void connectAndPlay(VideoComponent vc, String settings, String addr) throws UnknownHostException, IOException { // find this ip updateResource(); Socket skt = null; if (addr.length() > 0) { Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface n = (NetworkInterface) e.nextElement(); Enumeration<InetAddress> ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); if (!i.isLinkLocalAddress() && !i.isLoopbackAddress()) { pushLog("CLNT START IP:" + i.getHostAddress()); clientLoc = i.getHostAddress(); } } } serverLoc = addr; skt = new Socket(serverLoc, 45000); } else if (addr.length() == 0) { clientLoc = "127.0.0.1"; serverLoc = "127.0.0.1"; skt = new Socket("localhost", 45000); } skt.setReuseAddress(true); BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream())); out = new PrintWriter(skt.getOutputStream(), true); JSONObject portNeg = new JSONObject(in.readLine()); int port = portNeg.getInt("port"); System.out.println("Client port: " + port); JSONObject json_settings = new JSONObject(); json_settings.put("settings", attribute + " " + clientbw + " " + request); out.println(json_settings.toString()); pushLog("> SYS: CNCT SUCCESS"); startStreaming(vc, settings, port); pushLog("> CTRL: LISTENING FOR COMMANDS"); Scanner s = new Scanner(System.in); String line; JSONObject json_command; while (true) { line = s.nextLine(); json_command = new JSONObject(); json_command.put("command", line); // json_command.put("bandwidth", ""); out.println(json_command.toString()); if (line.equals("stop")) break; } in.close(); out.close(); skt.close(); }
@Override public NetworkState getState() { java.net.InetAddress jnAddress = getFirstActiveInetAddress(); if (jnAddress == null) { return NetworkState.DISCONNECTED; } else if (jnAddress.isLoopbackAddress() || jnAddress.isLinkLocalAddress()) { return NetworkState.CONNECTED_LOCAL; } else if (jnAddress.isSiteLocalAddress()) { return NetworkState.CONNECTED_SITE; } else { return NetworkState.CONNECTED_GLOBAL; } }
private synchronized void addLocalAddress(InetAddress addr) { int addrtype; if (addr.isLoopbackAddress()) { addrtype = HOSTMAP_LOOPBACK; } else if (addr.isLinkLocalAddress()) { addrtype = HOSTMAP_LINKLOCAL; } else if (addr.isSiteLocalAddress()) { addrtype = HOSTMAP_SITELOCAL; } else if (addr.isMulticastAddress()) { addrtype = HOSTMAP_MULTICAST; } else { addrtype = HOSTMAP_GLOBAL; } if (addr.getAddress().length == 4) { addrtype |= HOSTMAP_IPV4; } else { addrtype |= HOSTMAP_IPV6; } String addrAsString = addr.getHostAddress(); fLocalHostAddresses.put(addrAsString, Integer.valueOf(addrtype | HOSTMAP_ADDR)); if (0 == (addrtype & (HOSTMAP_LINKLOCAL | HOSTMAP_SITELOCAL | HOSTMAP_MULTICAST))) { // Don't do DNS Reverse Loopkup's for non-routable addresses. // They won't be known to the Name Server anyway, and they // make startup _much_ slower. String addrAsNameCan = addr.getCanonicalHostName().toLowerCase(); // query the name after the canonical name, it will re-use // cached canonical name (if the name was not explicitly set) String addrAsName = addr.getHostName().toLowerCase(); if (!addrAsNameCan.equals(addrAsString)) { // We must check if we really got a name, since InetAddress.getHostName() // returns the original address in case it thinks the name is spoofed! if (0 == (addrtype & HOSTMAP_LOOPBACK)) { // Not loopback --> found a Canonical Name. fLocalHostAddresses.put( addrAsNameCan, Integer.valueOf(addrtype | HOSTMAP_NAME | HOSTMAP_CANONICALNAME)); // override the address as canonical-address fLocalHostAddresses.put( addrAsString, Integer.valueOf(addrtype | HOSTMAP_ADDR | HOSTMAP_CANONICALADDR)); } else { // Loopback --> add the found name as non-canonical. fLocalHostAddresses.put(addrAsNameCan, Integer.valueOf(addrtype | HOSTMAP_NAME)); } } if (!addrAsName.equals(addrAsString) && !addrAsName.equals(addrAsNameCan)) { // don't override the canonical name by the name. fLocalHostAddresses.put(addrAsName, Integer.valueOf(addrtype | HOSTMAP_NAME)); } } }
private static InetAddress getLinkLocalAddress(String networkInterfaceName) throws SocketException { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) { if (networkInterfaceName == null || networkInterfaceName.equals(networkInterface.getName())) { Enumeration<InetAddress> ips = networkInterface.getInetAddresses(); for (InetAddress ip : Collections.list(ips)) { if (ip.isLinkLocalAddress()) { return ip; } } } } return null; }
public static void main(String[] args) { if (args.length == 0 || args == null) { System.out.println("Didn't enter argument!, Please enter like this."); System.out.println("ex. java IPCharateristics args[0] args[1] ..."); return; } try { InetAddress address = InetAddress.getByName(args[0]); if (address.isAnyLocalAddress()) { System.out.println(address + " is a wildcard address."); } if (address.isLoopbackAddress()) { System.out.println(address + " is a loopback address."); } if (address.isLinkLocalAddress()) { System.out.println(address + " is a link-local address."); } if (address.isSiteLocalAddress()) { System.out.println(address + " is a site-local address"); } else { System.out.println(address + " is a global address"); } if (address.isMulticastAddress()) { if (address.isMCGlobal()) { System.out.println(address + " is a global multicast address."); } else if (address.isMCOrgLocal()) { System.out.println(address + " is an organization wide multicast address."); } else if (address.isMCSiteLocal()) { System.out.println(address + " is a site wide multicast address."); } else if (address.isMCLinkLocal()) { System.out.println(address + " is a subnet wide multicast address."); } else if (address.isMCNodeLocal()) { System.out.println(address + " is an interface-local multicast address."); } else { System.out.println(address + " is an unknown multicast address type."); } } else { System.out.println(address + " is a unicast address."); } } catch (UnknownHostException ex) { System.out.println("Could not resolve " + args[0]); } }
/** * Returns an InetAddress instance that represents the localhost, and that a socket can bind upon * or distribute to peers as a contact address. * * @param intendedDestination the destination that we'd like to use the localhost address with. * @return an InetAddress instance representing the local host, and that a socket can bind upon or * distribute to peers as a contact address. */ public synchronized InetAddress getLocalHost(InetAddress intendedDestination) { // no point in making sure that the localHostFinderSocket is initialized. // better let it through a NullPointerException. InetAddress localHost = null; localHostFinderSocket.connect(intendedDestination, this.RANDOM_ADDR_DISC_PORT); localHost = localHostFinderSocket.getLocalAddress(); localHostFinderSocket.disconnect(); // windows socket implementations return the any address so we need to // find something else here ... InetAddress.getLocalHost seems to work // better on windows so lets hope it'll do the trick. if (localHost.isAnyLocalAddress()) { try { // all that's inside the if is an ugly IPv6 hack // (good ol' IPv6 - always causing more problems than it solves.) if (intendedDestination instanceof Inet6Address) { // return the first globally routable ipv6 address we find // on the machine (and hope it's a good one) Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface iface = (NetworkInterface) interfaces.nextElement(); Enumeration addresses = iface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = (InetAddress) addresses.nextElement(); if (address instanceof Inet6Address) { if (!address.isAnyLocalAddress() && !address.isLinkLocalAddress() && !address.isSiteLocalAddress() && !address.isLoopbackAddress()) { return address; } } } } } else localHost = InetAddress.getLocalHost(); /** @todo test on windows for ipv6 cases */ } catch (Exception ex) { // sigh ... ok return 0.0.0.0 logger.warn("Failed to get localhost ", ex); } } return localHost; }
private Pair<String, Integer> validateUrl(String url) throws IllegalArgumentException { try { URI uri = new URI(url); if (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https")) { throw new IllegalArgumentException("Unsupported scheme for url"); } int port = uri.getPort(); if (!(port == 80 || port == 443 || port == -1)) { throw new IllegalArgumentException("Only ports 80 and 443 are allowed"); } if (port == -1 && uri.getScheme().equalsIgnoreCase("https")) { port = 443; } else if (port == -1 && uri.getScheme().equalsIgnoreCase("http")) { port = 80; } String host = uri.getHost(); try { InetAddress hostAddr = InetAddress.getByName(host); if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress()) { throw new IllegalArgumentException("Illegal host specified in url"); } if (hostAddr instanceof Inet6Address) { throw new IllegalArgumentException( "IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")"); } return new Pair<String, Integer>(host, port); } catch (UnknownHostException uhe) { throw new IllegalArgumentException("Unable to resolve " + host); } } catch (IllegalArgumentException iae) { s_logger.warn("Failed uri validation check: " + iae.getMessage()); throw iae; } catch (URISyntaxException use) { s_logger.warn("Failed uri syntax check: " + use.getMessage()); throw new IllegalArgumentException(use.getMessage()); } }
boolean shouldIgnorePacket(DatagramPacket packet) { boolean result = false; if (this.getInetAddress() != null) { InetAddress from = packet.getAddress(); if (from != null) { if (from.isLinkLocalAddress() && (!this.getInetAddress().isLinkLocalAddress())) { // Ignore linklocal packets on regular interfaces, unless this is // also a linklocal interface. This is to avoid duplicates. This is // a terrible hack caused by the lack of an API to get the address // of the interface on which the packet was received. result = true; } if (from.isLoopbackAddress() && (!this.getInetAddress().isLoopbackAddress())) { // Ignore loopback packets on a regular interface unless this is also a loopback // interface. result = true; } } } return result; }
private static String getLocalPeerIP() throws SocketException { String result = null; Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface nic = (NetworkInterface) e.nextElement(); System.out.println("Net interface: " + nic.getName()); Enumeration<InetAddress> e2 = nic.getInetAddresses(); while (e2.hasMoreElements()) { InetAddress ip = (InetAddress) e2.nextElement(); if (!ip.isLinkLocalAddress() && !ip.isLoopbackAddress()) { return ip.getHostAddress(); } } } System.out.println(result); return null; }
private static void init() { // first way to get local IP try { localAddr = InetAddress.getLocalHost(); logger.info("local IP:" + localAddr.getHostAddress()); } catch (UnknownHostException e) { logger.info("try again\n"); } if (localAddr != null) { return; } // other way to get local IP Enumeration<InetAddress> localAddrs; try { // modify your network interface name NetworkInterface ni = NetworkInterface.getByName(networkInterface); if (ni == null) { return; } localAddrs = ni.getInetAddresses(); if (localAddrs == null || !localAddrs.hasMoreElements()) { logger.error("choose NetworkInterface\n" + getNetworkInterface()); return; } while (localAddrs.hasMoreElements()) { InetAddress tmp = localAddrs.nextElement(); if (!tmp.isLoopbackAddress() && !tmp.isLinkLocalAddress() && !(tmp instanceof Inet6Address)) { localAddr = tmp; logger.info("local IP:" + localAddr.getHostAddress()); break; } } } catch (Exception e) { logger.error("Failure when init ProxyUtil", e); logger.error("choose NetworkInterface\n" + getNetworkInterface()); } }
public static List<String> getPublicIPs6() { List<String> ips6 = new ArrayList<String>(); Enumeration<NetworkInterface> ifs; try { ifs = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { e.printStackTrace(); return ips6; } while (ifs.hasMoreElements()) { NetworkInterface iface = ifs.nextElement(); Enumeration<InetAddress> iad = iface.getInetAddresses(); while (iad.hasMoreElements()) { InetAddress localIP = iad.nextElement(); if (!localIP.isSiteLocalAddress() && !localIP.isLinkLocalAddress() && !localIP.isLoopbackAddress()) { if (localIP instanceof java.net.Inet6Address) ips6.add(localIP.getHostAddress()); } } } return ips6; }
/** * 获取ip地址 * * @return */ public static String getLocalIpAddress() { 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 (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) { String ip_str = inetAddress.getHostAddress(); System.out.print("IpAddress=" + ip_str); Log.i(TAG, "IpAddress=" + ip_str); if (!TextUtils.isEmpty(ip_str)) { return ip_str; } } } } } catch (SocketException ex) { Log.e(TAG, "WifiPreference IpAddress", ex); } return null; }
private static boolean shouldInclude( InetAddress ia, boolean includeSiteLocal, boolean includeLoopbackAndWildcard, boolean includeIPv6) { return (!ia.isLinkLocalAddress()) && // 169.254.x.x (!ia.isMulticastAddress()) && (includeLoopbackAndWildcard || ((!ia.isAnyLocalAddress()) && (!ia.isLoopbackAddress()))) && (includeSiteLocal || ((!ia.isSiteLocalAddress()) && // disallow fc00::/8 and fd00::/8 (Unique local addresses RFC 4193) // not recognized as local by InetAddress (ia.getAddress().length != 16 || (ia.getAddress()[0] & 0xfe) != 0xfc))) && // Hamachi 5/8 allocated to RIPE (30 November 2010) // Removed from TransportImpl.isPubliclyRoutable() // Check moved to here, for now, but will eventually need to // remove it from here also. // (includeLocal || // (!ia.getHostAddress().startsWith("5."))) && (includeIPv6 || (ia instanceof Inet4Address)); }
private String validateUrl(String url) { try { URI uri = new URI(url); if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https") && !uri.getScheme().equalsIgnoreCase("file"))) { throw new IllegalArgumentException("Unsupported scheme for url: " + url); } int port = uri.getPort(); if (!(port == 80 || port == 443 || port == -1)) { throw new IllegalArgumentException("Only ports 80 and 443 are allowed"); } String host = uri.getHost(); try { InetAddress hostAddr = InetAddress.getByName(host); if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress()) { throw new IllegalArgumentException("Illegal host specified in url"); } if (hostAddr instanceof Inet6Address) { throw new IllegalArgumentException( "IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")"); } } catch (UnknownHostException uhe) { throw new IllegalArgumentException("Unable to resolve " + host); } return uri.toString(); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URL " + url); } }
/** * Gets a list of all network interfaces available on the local system or {@code null} if no * interface is available. * * @return the list of {@code NetworkInterface} instances representing the available interfaces. * @throws SocketException if an error occurs while getting the network interface information. */ public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException { NetworkInterface[] interfaces = getNetworkInterfacesImpl(); if (interfaces == null) { return null; } for (NetworkInterface netif : interfaces) { // Ensure that current NetworkInterface is bound to at least // one InetAddress before processing if (netif.addresses != null) { for (InetAddress addr : netif.addresses) { if (16 == addr.ipaddress.length) { if (addr.isLinkLocalAddress() || addr.isSiteLocalAddress()) { ((Inet6Address) addr).scopedIf = netif; ((Inet6Address) addr).ifname = netif.name; ((Inet6Address) addr).scope_ifname_set = true; } } } } } return (new Vector<NetworkInterface>(Arrays.asList(interfaces))).elements(); }
private static boolean acceptableAddress(InetAddress address) { return address != null && !address.isLoopbackAddress() && !address.isAnyLocalAddress() && !address.isLinkLocalAddress(); }
private static Map<NetworkInterface, Set<InetAddress>> selectInterfaceAndAddress( Map<NetworkInterface, Set<InetAddress>> acceptable) throws SocketException { // Give preference to NetworkInterfaces that are 1) up, 2) not loopback 3) not point-to-point. // If any of these criteria eliminate all interfaces, discard it. if (acceptable.size() > 1) { Map<NetworkInterface, Set<InetAddress>> preferred = new HashMap<NetworkInterface, Set<InetAddress>>(); for (NetworkInterface ni : acceptable.keySet()) { if (ni.isUp()) { preferred.put(ni, acceptable.get(ni)); } } if (preferred.size() > 0) { acceptable = preferred; } // else this preference eliminates all interfaces, so ignore it } if (acceptable.size() > 1) { Map<NetworkInterface, Set<InetAddress>> preferred = new HashMap<NetworkInterface, Set<InetAddress>>(); for (NetworkInterface ni : acceptable.keySet()) { if (!ni.isLoopback()) { preferred.put(ni, acceptable.get(ni)); } } if (preferred.size() > 0) { acceptable = preferred; } // else this preference eliminates all interfaces, so ignore it } if (acceptable.size() > 1) { Map<NetworkInterface, Set<InetAddress>> preferred = new HashMap<NetworkInterface, Set<InetAddress>>(); for (NetworkInterface ni : acceptable.keySet()) { if (!ni.isPointToPoint()) { preferred.put(ni, acceptable.get(ni)); } } if (preferred.size() > 0) { acceptable = preferred; } // else this preference eliminates all interfaces, so ignore it } if (hasMultipleMatches(acceptable)) { // Give preference to non-link-local addresses Map<NetworkInterface, Set<InetAddress>> preferred = new HashMap<NetworkInterface, Set<InetAddress>>(); for (Map.Entry<NetworkInterface, Set<InetAddress>> entry : acceptable.entrySet()) { Set<InetAddress> acceptableAddresses = entry.getValue(); if (acceptableAddresses.size() > 1) { Set<InetAddress> preferredAddresses = null; for (InetAddress addr : acceptableAddresses) { if (!addr.isLinkLocalAddress()) { if (preferredAddresses == null) { preferredAddresses = new HashSet<InetAddress>(); preferred.put(entry.getKey(), preferredAddresses); } preferredAddresses.add(addr); } } } else { acceptable.put(entry.getKey(), acceptableAddresses); } } if (preferred.size() > 0) { acceptable = preferred; } // else this preference eliminates all interfaces, so ignore it } Map.Entry<NetworkInterface, Set<InetAddress>> entry = acceptable.entrySet().iterator().next(); return Collections.singletonMap( entry.getKey(), Collections.singleton(entry.getValue().iterator().next())); }