List of usage examples for java.net InetAddress getHostAddress
public String getHostAddress()
From source file:com.carreygroup.JARVIS.Demon.java
/** * Get IP address from first non-localhost interface * @param ipv4 true=return ipv4, false=return ipv6 * @return address or empty string//from www. j a va2 s. co m */ public static String getLoaclIPAddress(boolean useIPv4) { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); if (useIPv4) { if (isIPv4) return sAddr; } else { if (!isIPv4) { int delim = sAddr.indexOf('%'); // drop ip6 port suffix return delim < 0 ? sAddr : sAddr.substring(0, delim); } } } } } } catch (Exception ex) { } // for now eat exceptions return ""; }
From source file:com.max2idea.android.fwknop.Fwknop.java
public static String getLocalIpAddress() { try {/*from w w w. j a v a 2 s. c o m*/ 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()) { Log.v("Internal ip", inetAddress.getHostAddress().toString()); return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { Log.e("Internal IP", ex.toString()); } return null; }
From source file:com.qwazr.server.configuration.ServerConfiguration.java
/** * Manage that kind of pattern:/*from w w w .j a v a 2 s . com*/ * 192.168.0.0/16,172.168.0.0/16 * 192.168.0.0/16 * 10.3.12.12 * * @param addressPattern a mask or an ip address * @param collect a collection filled with the matching addresses * @throws SocketException */ private static void findMatchingAddress(final String addressPattern, final Collection<String> collect) throws SocketException { final String[] patterns = StringUtils.split(addressPattern, ",; "); if (patterns == null) return; for (String pattern : patterns) { if (pattern == null) continue; pattern = pattern.trim(); if (!pattern.contains("/")) { collect.add(pattern); continue; } final SubnetUtils.SubnetInfo subnet = pattern.contains("/") ? new SubnetUtils(pattern).getInfo() : null; final Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces(); while (enumInterfaces != null && enumInterfaces.hasMoreElements()) { final NetworkInterface ifc = enumInterfaces.nextElement(); if (!ifc.isUp()) continue; final Enumeration<InetAddress> enumAddresses = ifc.getInetAddresses(); while (enumAddresses != null && enumAddresses.hasMoreElements()) { final InetAddress inetAddress = enumAddresses.nextElement(); if (!(inetAddress instanceof Inet4Address)) continue; final String address = inetAddress.getHostAddress(); if (subnet != null && subnet.isInRange(address) || address.equals(pattern)) collect.add(address); } } } }
From source file:org.apache.synapse.transport.nhttp.DefaultHttpGetProcessor.java
/** * Whatever this method returns as the IP is ignored by the actual http/s listener when * its getServiceEPR is invoked. This was originally copied from axis2 * * @return Returns String.// ww w .j a v a 2 s . c o m * @throws java.net.SocketException if the socket can not be accessed */ protected static String getIpAddress() throws SocketException { Enumeration e = NetworkInterface.getNetworkInterfaces(); String address = "127.0.0.1"; while (e.hasMoreElements()) { NetworkInterface netface = (NetworkInterface) e.nextElement(); Enumeration addresses = netface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress ip = (InetAddress) addresses.nextElement(); if (!ip.isLoopbackAddress() && isIP(ip.getHostAddress())) { return ip.getHostAddress(); } } } return address; }
From source file:net.itransformers.idiscover.discoveryhelpers.xml.SnmpForXslt.java
public static String getNameByDNS(String ipAddress) { if (mockSnmpForXslt != null) { return mockSnmpForXslt.getNameByDNS(ipAddress); }/*from ww w. j a va 2 s. c om*/ // InetAddress inetAddress = new InetAddress(); InetAddress address = null; try { address = InetAddress.getByName(ipAddress); } catch (UnknownHostException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return address.getHostAddress(); }
From source file:com.screenslicer.common.CommonUtil.java
public static String ip() { if (myIp != null) { return myIp; }//from w ww . ja v a 2 s. c o m try { Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); while (ifaces.hasMoreElements()) { NetworkInterface iface = ifaces.nextElement(); Enumeration<InetAddress> addrs = iface.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr = addrs.nextElement(); String ip = addr.getHostAddress(); if (ip.contains(".") && !ip.startsWith("127.") && !ip.startsWith("192.168.") && !ip.startsWith("10.") && !ip.startsWith("172.16.") && !ip.startsWith("172.17.") && !ip.startsWith("172.18.") && !ip.startsWith("172.19.") && !ip.startsWith("172.20.") && !ip.startsWith("172.21.") && !ip.startsWith("172.22.") && !ip.startsWith("172.23.") && !ip.startsWith("172.24.") && !ip.startsWith("172.25.") && !ip.startsWith("172.26.") && !ip.startsWith("172.27.") && !ip.startsWith("172.28.") && !ip.startsWith("172.29.") && !ip.startsWith("172.30.") && !ip.startsWith("172.31.") && !ip.startsWith("169.254.") && !ip.startsWith("224.") && !ip.startsWith("225.") && !ip.startsWith("226.") && !ip.startsWith("227.") && !ip.startsWith("228.") && !ip.startsWith("229.") && !ip.startsWith("230.") && !ip.startsWith("231.") && !ip.startsWith("232.") && !ip.startsWith("233.") && !ip.startsWith("234.") && !ip.startsWith("235.") && !ip.startsWith("236.") && !ip.startsWith("237.") && !ip.startsWith("238.") && !ip.startsWith("239.") && !ip.startsWith("255.255.255.255")) { return ip; } } } } catch (SocketException e) { Log.exception(e); } return "127.0.0.1"; }
From source file:Main.java
public static String filterIP(final InetAddress inetAddress) { try {/*from ww w .ja v a 2 s. co m*/ final String ipVersion; if (inetAddress instanceof Inet4Address) ipVersion = "ipv4"; else if (inetAddress instanceof Inet6Address) ipVersion = "ipv6"; else ipVersion = "ipv?"; if (inetAddress.isAnyLocalAddress()) return "wildcard"; if (inetAddress.isSiteLocalAddress()) return "site_local_" + ipVersion; if (inetAddress.isLinkLocalAddress()) return "link_local_" + ipVersion; if (inetAddress.isLoopbackAddress()) return "loopback_" + ipVersion; return inetAddress.getHostAddress(); } catch (final IllegalArgumentException e) { return "illegal_ip"; } }
From source file:net.pms.network.UPNPHelper.java
/** * Starts up two threads: one to broadcast UPnP ALIVE messages and another * to listen for responses. /*from www . j ava2 s . c o m*/ * * @throws IOException Signals that an I/O exception has occurred. */ public static void listen() throws IOException { Runnable rAlive = new Runnable() { @Override public void run() { int delay = 10000; while (true) { sleep(delay); sendAlive(); // The first delay for sending an ALIVE message is 10 seconds, // the second delay is for 20 seconds. From then on, all other // delays are for 180 seconds. switch (delay) { case 10000: delay = 20000; break; case 20000: delay = 180000; break; } } } }; aliveThread = new Thread(rAlive, "UPNP-AliveMessageSender"); aliveThread.start(); Runnable r = new Runnable() { @Override public void run() { boolean bindErrorReported = false; while (true) { MulticastSocket multicastSocket = null; try { // Use configurable source port as per http://code.google.com/p/ps3mediaserver/issues/detail?id=1166 multicastSocket = new MulticastSocket(configuration.getUpnpPort()); if (bindErrorReported) { logger.warn( "Finally, acquiring port " + configuration.getUpnpPort() + " was successful!"); } NetworkInterface ni = NetworkConfiguration.getInstance().getNetworkInterfaceByServerName(); try { // Setting the network interface will throw a SocketException on Mac OSX // with Java 1.6.0_45 or higher, but if we don't do it some Windows // configurations will not listen at all. if (ni != null) { multicastSocket.setNetworkInterface(ni); } else if (PMS.get().getServer().getNetworkInterface() != null) { multicastSocket.setNetworkInterface(PMS.get().getServer().getNetworkInterface()); logger.trace("Setting multicast network interface: " + PMS.get().getServer().getNetworkInterface()); } } catch (SocketException e) { // Not setting the network interface will work just fine on Mac OSX. } multicastSocket.setTimeToLive(4); multicastSocket.setReuseAddress(true); InetAddress upnpAddress = getUPNPAddress(); multicastSocket.joinGroup(upnpAddress); while (true) { byte[] buf = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(buf, buf.length); multicastSocket.receive(receivePacket); String s = new String(receivePacket.getData()); InetAddress address = receivePacket.getAddress(); if (s.startsWith("M-SEARCH")) { String remoteAddr = address.getHostAddress(); int remotePort = receivePacket.getPort(); if (configuration.getIpFiltering().allowed(address)) { logger.trace( "Receiving a M-SEARCH from [" + remoteAddr + ":" + remotePort + "]"); if (StringUtils.indexOf(s, "urn:schemas-upnp-org:service:ContentDirectory:1") > 0) { sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:service:ContentDirectory:1"); } if (StringUtils.indexOf(s, "upnp:rootdevice") > 0) { sendDiscover(remoteAddr, remotePort, "upnp:rootdevice"); } if (StringUtils.indexOf(s, "urn:schemas-upnp-org:device:MediaServer:1") > 0) { sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:device:MediaServer:1"); } if (StringUtils.indexOf(s, "ssdp:all") > 0) { sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:device:MediaServer:1"); } if (StringUtils.indexOf(s, PMS.get().usn()) > 0) { sendDiscover(remoteAddr, remotePort, PMS.get().usn()); } } } else if (s.startsWith("NOTIFY")) { String remoteAddr = address.getHostAddress(); int remotePort = receivePacket.getPort(); logger.trace("Receiving a NOTIFY from [" + remoteAddr + ":" + remotePort + "]"); } } } catch (BindException e) { if (!bindErrorReported) { logger.error("Unable to bind to " + configuration.getUpnpPort() + ", which means that PMS will not automatically appear on your renderer! " + "This usually means that another program occupies the port. Please " + "stop the other program and free up the port. " + "PMS will keep trying to bind to it...[" + e.getMessage() + "]"); } bindErrorReported = true; sleep(5000); } catch (IOException e) { logger.error("UPNP network exception", e); sleep(1000); } finally { if (multicastSocket != null) { // Clean up the multicast socket nicely try { InetAddress upnpAddress = getUPNPAddress(); multicastSocket.leaveGroup(upnpAddress); } catch (IOException e) { } multicastSocket.disconnect(); multicastSocket.close(); } } } } }; listenerThread = new Thread(r, "UPNPHelper"); listenerThread.start(); }
From source file:edu.usc.pgroup.floe.utils.Utils.java
/** * returns the canonical host name. This assumes a unique host name for * each machine in the cluster does not apply. * FixMe: In local cloud environment (local eucalyptus in system mode) * where the DNS server is not running, this might be an issue. * @return The first IPv4 address found for any interface that is up and * running./*from w ww .j a v a2s .c o m*/ */ public static String getIpAddress() { String ip = null; try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); LOGGER.error("Getting ip"); while (interfaces.hasMoreElements()) { LOGGER.error("Next iface"); NetworkInterface current = interfaces.nextElement(); if (!current.isUp() || current.isLoopback() || current.isVirtual()) { continue; } Enumeration<InetAddress> addresses = current.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress currentAddr = addresses.nextElement(); if (currentAddr.isLoopbackAddress() || (currentAddr instanceof Inet6Address)) { continue; } ip = currentAddr.getHostAddress(); } } } catch (SocketException e) { LOGGER.error("Error occurred while retrieving hostname" + e.getMessage()); throw new RuntimeException("Error occurred while " + "retrieving hostname" + e.getMessage()); } return ip; }
From source file:com.clustercontrol.agent.Agent.java
public static AgentInfo getAgentInfo() { // IP???????agentInfo?????? if (ReceiveTopic.isReloadFlg()) { return agentInfo; }// www.j a va 2 s . com agentInfo.setFacilityId(AgentProperties.getProperty("facilityId")); String instanceId = AgentProperties.getProperty("instanceId"); if (instanceId == null) { instanceId = ""; } agentInfo.setInstanceId(instanceId); // OS(?????IP) try { // ??? String hostname = System.getProperty("hostname"); m_log.debug("hostname=[" + hostname + "]"); agentInfo.setHostname(hostname); // IP? Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); ArrayList<String> newIpAddressList = new ArrayList<String>(); if (null != networkInterfaces) { while (networkInterfaces.hasMoreElements()) { NetworkInterface ni = networkInterfaces.nextElement(); Enumeration<InetAddress> inetAddresses = ni.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress in = inetAddresses.nextElement(); String hostAddress = in.getHostAddress(); if (hostAddress != null && !hostAddress.equals("127.0.0.1") && !hostAddress.startsWith("0:0:0:0:0:0:0:1") && !hostAddress.equals("::1")) { newIpAddressList.add(hostAddress); } } } } if (agentInfo.getIpAddress().size() != newIpAddressList.size()) { m_log.info("ipAddress change : " + agentInfo.getIpAddress().size() + "," + newIpAddressList.size()); agentInfo.getIpAddress().clear(); agentInfo.getIpAddress().addAll(newIpAddressList); ReceiveTopic.setReloadFlg(true); } else { if (!agentInfo.getIpAddress().containsAll(newIpAddressList)) { m_log.info("ipAddress change"); agentInfo.getIpAddress().clear(); agentInfo.getIpAddress().addAll(newIpAddressList); ReceiveTopic.setReloadFlg(true); } } } catch (SocketException e) { m_log.error(e, e); } agentInfo.setInterval(ReceiveTopic.getTopicInterval()); m_log.debug(getAgentStr()); return agentInfo; }