List of usage examples for java.net InetAddress getHostAddress
public String getHostAddress()
From source file:com.buaa.cfs.net.DNS.java
/** * Returns all the IPs associated with the provided interface, if any, in textual form. * * @param strInterface The name of the network interface or sub-interface to query (eg eth0 or eth0:0) or the * string "default" * @param returnSubinterfaces Whether to return IPs associated with subinterfaces of the given interface * * @return A string vector of all the IPs associated with the provided interface. The local host IP is returned if * the interface name "default" is specified or there is an I/O error looking for the given interface. * * @throws UnknownHostException If the given interface is invalid *///from w ww .ja va 2 s . com public static String[] getIPs(String strInterface, boolean returnSubinterfaces) throws UnknownHostException { if ("default".equals(strInterface)) { return new String[] { cachedHostAddress }; } NetworkInterface netIf; try { netIf = NetworkInterface.getByName(strInterface); if (netIf == null) { netIf = getSubinterface(strInterface); } } catch (SocketException e) { LOG.warn("I/O error finding interface " + strInterface + ": " + e.getMessage()); return new String[] { cachedHostAddress }; } if (netIf == null) { throw new UnknownHostException("No such interface " + strInterface); } // NB: Using a LinkedHashSet to preserve the order for callers // that depend on a particular element being 1st in the array. // For example, getDefaultIP always returns the first element. LinkedHashSet<InetAddress> allAddrs = new LinkedHashSet<InetAddress>(); allAddrs.addAll(Collections.list(netIf.getInetAddresses())); if (!returnSubinterfaces) { allAddrs.removeAll(getSubinterfaceInetAddrs(netIf)); } String ips[] = new String[allAddrs.size()]; int i = 0; for (InetAddress addr : allAddrs) { ips[i++] = addr.getHostAddress(); } return ips; }
From source file:hsyndicate.utils.IPUtils.java
public static Collection<String> getHostAddress() { if (!cachedHostAddr.isEmpty()) { return Collections.unmodifiableCollection(cachedHostAddr); } else {/*w w w . j a v a 2s. co m*/ try { Enumeration e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface n = (NetworkInterface) e.nextElement(); Enumeration ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); String hostAddress = i.getHostAddress(); if (isProperHostAddress(hostAddress)) { if (!cachedHostAddr.contains(hostAddress)) { cachedHostAddr.add(hostAddress); } } String hostName = i.getHostName(); if (isProperHostAddress(hostName)) { if (!cachedHostAddr.contains(hostName)) { cachedHostAddr.add(hostName); } } String canonicalHostName = i.getCanonicalHostName(); if (isProperHostAddress(canonicalHostName)) { if (!cachedHostAddr.contains(canonicalHostName)) { cachedHostAddr.add(canonicalHostName); } } } } } catch (SocketException ex) { LOG.error("Exception occurred while scanning local interfaces", ex); } return Collections.unmodifiableCollection(cachedHostAddr); } }
From source file:edu.uci.ics.hyracks.imru.jobgen.ClusterConfig.java
/** * Set location constraints for an operator based on the locations of input * files in HDFS. Randomly assigns partitions to NCs where the HDFS files * are local; assigns the rest randomly. * /* w ww . ja v a2s .c om*/ * @param spec * A job specification. * @param operator * The operator that will be constrained. * @param splits * A list of InputSplits specifying files in HDFS. * @param random * A source of randomness (so the partition-assignment can be * repeated across iterations, provided that the HDFS file * locations don't change). * @return The assigned partition locations. * @throws IOException * @throws HyracksException */ public static String[] setLocationConstraint(JobSpecification spec, IMRUOperatorDescriptor operator, InputSplit[] hdfsSplits, IMRUFileSplit[] splits, Random random) throws IOException { if (NCs == null) loadClusterConfig(); if (splits.length == 0) return new String[0]; if (hdfsSplits == null) { int partitionCount = splits.length; String[] partitionLocations = new String[partitionCount]; for (int partition = 0; partition < partitionCount; partition++) { int pos = partition % NCs.length; String path = splits[partition].getPath(); int t = path.indexOf(":"); if (t > 0) partitionLocations[partition] = path.substring(0, t); else partitionLocations[partition] = NCs[pos]; } if (operator != null) { PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, operator, partitionLocations); PartitionConstraintHelper.addPartitionCountConstraint(spec, operator, partitionCount); } return partitionLocations; } int partitionCount = splits.length; String[] partitionLocations = new String[partitionCount]; int localAssignments = 0; int nonlocalAssignments = 0; for (int partition = 0; partition < partitionCount; partition++) { String[] localHosts = hdfsSplits[partition].getLocations(); // Remove nondeterminism from the call to getLocations(): Collections.sort(Arrays.asList(localHosts)); Collections.shuffle(Arrays.asList(localHosts), random); if (localHosts.length > 0) { LOG.info("Partition " + partition + " is local at " + localHosts.length + " hosts: " + StringUtils.join(localHosts, ", ")); for (int host = 0; host < localHosts.length; host++) { InetAddress[] hostIps = InetAddress.getAllByName(localHosts[host]); for (InetAddress ip : hostIps) { if (ipToNcMapping.get(ip.getHostAddress()) != null) { List<String> ncs = ipToNcMapping.get(ip.getHostAddress()); int pos = random.nextInt(ncs.size()); partitionLocations[partition] = ncs.get(pos); LOG.info("Partition " + partition + " assigned to " + ncs.get(pos) + ", where it is local."); localAssignments++; break; } } if (partitionLocations[partition] != null) { break; } } if (partitionLocations[partition] == null) { int pos = random.nextInt(NCs.length); partitionLocations[partition] = NCs[pos]; nonlocalAssignments++; LOG.info("Partition " + partition + " assigned to " + NCs[pos] + " because there is no NC where it is local."); } } else { int pos = random.nextInt(NCs.length); partitionLocations[partition] = NCs[pos]; nonlocalAssignments++; LOG.info("Partition " + partition + " assigned to " + NCs[pos] + " becasue getLocations() returned no locations."); } } if (LOG.isLoggable(Level.INFO)) { LOG.info("NC partition counts:"); Map<String, MutableInt> ncPartitionCounts = new HashMap<String, MutableInt>(); for (int i = 0; i < partitionLocations.length; i++) { if (ncPartitionCounts.get(partitionLocations[i]) == null) { ncPartitionCounts.put(partitionLocations[i], new MutableInt(1)); } else { ncPartitionCounts.get(partitionLocations[i]).increment(); } } for (Map.Entry<String, MutableInt> entry : ncPartitionCounts.entrySet()) { LOG.info(entry.getKey() + ": " + entry.getValue().intValue() + " partitions"); } } double localityPercentage = ((1.0 * localAssignments) / (localAssignments + nonlocalAssignments)) * 100; if (operator != null) { LOG.info(operator.getClass().getSimpleName() + ": " + localAssignments + " local; " + nonlocalAssignments + " non-local; " + localityPercentage + "% locality"); PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, operator, partitionLocations); PartitionConstraintHelper.addPartitionCountConstraint(spec, operator, partitionCount); } return partitionLocations; }
From source file:eu.stratosphere.nephele.net.NetUtils.java
/** * Given a string representation of a host, return its ip address * in textual presentation.//from w w w . j a v a 2 s .c om * * @param name * a string representation of a host: * either a textual representation its IP address or its host name * @return its IP address in the string format */ public static String normalizeHostName(String name) { if (Character.digit(name.charAt(0), 16) != -1) { // it is an IP return name; } else { try { InetAddress ipAddress = InetAddress.getByName(name); return ipAddress.getHostAddress(); } catch (UnknownHostException e) { return name; } } }
From source file:wuit.crawler.searcher.Crawler.java
public static void getUrlInfo(DSCrawlerUrl info) { try {/*from w ww. java 2s. c om*/ URL _url = new URL(info.url); info.dns = _url.getHost() + ""; info.path = _url.getPath(); info.file = _url.getProtocol(); if (!info.url.equals("") && info.url != null) { InetAddress a = InetAddress.getByName(_url.getHost()); if (a != null) info.IP = a.getHostAddress(); } } catch (Exception e) { System.out.println(" crawler " + e.getMessage()); } }
From source file:com.moss.greenshell.wizard.catastrophe.PostMortemScreen.java
public static void submitErrorReport(final Throwable cause, final ErrorReportDecorator... decorators) throws Exception { List<ErrorReportChunk> chunks = new LinkedList<ErrorReportChunk>(); try {//w ww. ja va 2s . co m if (cause instanceof InternalErrorException) { InternalErrorException ie = (InternalErrorException) cause; ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain", ie.id().getBytes("UTF8")); chunks.add(chunk); } else if (cause instanceof SOAPFaultException) { SOAPFaultException soapFault = (SOAPFaultException) cause; String content = soapFault.getFault().getFirstChild().getTextContent(); String prefix = "Internal Service Error Occurred: "; if (content.startsWith(prefix)) { String id = content.substring(prefix.length()); ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain", id.getBytes("UTF8")); chunks.add(chunk); } } } catch (Throwable t) { t.printStackTrace(); } // STACK TRACE ByteArrayOutputStream stackBytes = new ByteArrayOutputStream(); PrintStream stackPrintStream = new PrintStream(stackBytes); cause.printStackTrace(stackPrintStream); stackPrintStream.close(); stackBytes.close(); ErrorReportChunk chunk = new ErrorReportChunk("stack trace", "text/plain", stackBytes.toByteArray()); chunks.add(chunk); // THREAD DUMP ByteArrayOutputStream dumpBytes = new ByteArrayOutputStream(); PrintStream out = new PrintStream(dumpBytes); Map<Thread, StackTraceElement[]> traceMap = Thread.getAllStackTraces(); for (Map.Entry<Thread, StackTraceElement[]> next : traceMap.entrySet()) { out.println(); out.println(next.getKey().getName()); for (StackTraceElement line : next.getValue()) { String className = emptyIfNull(line.getClassName()); String methodName = emptyIfNull(line.getMethodName()); String fileName = emptyIfNull(line.getFileName()); out.println(" " + className + "." + methodName + " (" + fileName + " line " + line.getLineNumber() + ")"); } } out.flush(); out.close(); ErrorReportChunk stackDump = new ErrorReportChunk("thread dump", "text/plain", dumpBytes.toByteArray()); chunks.add(stackDump); // SYSTEM PROPERTIES ByteArrayOutputStream propsBytes = new ByteArrayOutputStream(); PrintStream propsOut = new PrintStream(propsBytes); for (Map.Entry<Object, Object> next : System.getProperties().entrySet()) { propsOut.println(" " + next.getKey() + "=" + next.getValue()); } propsOut.flush(); propsOut.close(); chunks.add(new ErrorReportChunk("system properties", "text/plain", propsBytes.toByteArray())); // LOCAL CLOCK chunks.add(new ErrorReportChunk("local clock", "text/plain", new DateTime().toString().getBytes())); // NETWORKING StringBuffer networking = new StringBuffer(); Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); while (ifaces.hasMoreElements()) { NetworkInterface iface = ifaces.nextElement(); networking.append("INTERFACE: " + iface.getName() + " (" + iface.getDisplayName() + ")\n"); Enumeration<InetAddress> addresses = iface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); networking.append(" Address:" + address.getHostAddress() + "\n"); networking.append(" Cannonical Host Name: " + address.getCanonicalHostName() + "\n"); networking.append(" Host Name: " + address.getHostName() + "\n"); } } chunks.add(new ErrorReportChunk("network configuration", "text/plain", networking.toString().getBytes())); // DECORATORS if (decorators != null) { for (ErrorReportDecorator decorator : decorators) { chunks.addAll(decorator.makeChunks(cause)); } } ErrorReport report = new ErrorReport(chunks); Reporter reporter = new Reporter(); ReportId id = reporter.submitReport(report); }
From source file:net.centro.rtb.monitoringcenter.infos.NodeInfo.java
private static String detectLoadBalancerIpAddress() { Enumeration<NetworkInterface> networkInterfaces = null; try {//from w w w . j a v a 2 s.c om networkInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { logger.debug("Unable to obtain network interfaces!", e); return null; } for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) { boolean isLoopback = false; try { isLoopback = networkInterface.isLoopback(); } catch (SocketException e) { logger.debug("Unable to identify if a network interface is a loopback or not"); continue; } if (isLoopback) { Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress inetAddress = inetAddresses.nextElement(); if (!inetAddress.isLoopbackAddress() && Inet4Address.class.isInstance(inetAddress)) { return inetAddress.getHostAddress(); } } } } return null; }
From source file:de.pawlidi.openaletheia.utils.AletheiaUtils.java
private static String getLocalhostAddress() { String localhostAdress = null; try {// w ww . j a va2 s . co m final InetAddress localHost = InetAddress.getLocalHost(); if (localHost != null) { localhostAdress = localHost.getHostAddress(); } } catch (UnknownHostException ex) { // ignore exception } return localhostAdress; }
From source file:com.alibaba.jstorm.utils.NetWorkUtils.java
public static String host2Ip(String host) { InetAddress address = null; try {//from w w w.j a v a 2s. c om address = InetAddress.getByName(host); } catch (UnknownHostException e) { LOG.warn("NetWorkUtil can't transfer hostname(" + host + ") to ip, return hostname", e); return host; } return address.getHostAddress(); }
From source file:gemlite.core.internal.support.system.ServerConfigHelper.java
private synchronized static void initConfig0(String envFile) { try {/*from www . ja v a 2 s . co m*/ Enumeration<URL> envs = ServerConfigHelper.class.getClassLoader().getResources(envFile); List<URL> list = new ArrayList<>(); while (envs.hasMoreElements()) { list.add(envs.nextElement()); } for (int i = list.size() - 1; i >= 0; i--) { URL url = list.get(i); System.out.println("Load env from:" + url); Properties prop = new Properties(); prop.load(url.openStream()); serverConfig.putAll(prop); } // String url=ServerConfigHelper.class.getClassLoader().getResource(envFile).toString(); // System.out.println("Load env from:"+url); // serverConfig.load(ServerConfigHelper.class.getClassLoader().getResourceAsStream(envFile)); } catch (IOException e) { e.printStackTrace(); initlized.set(false); } List<Object> names = new ArrayList<>(serverConfig.keySet()); Collections.sort(names, new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } }); Iterator<Object> it = names.iterator(); while (it.hasNext()) { String key = it.next().toString(); // String value = serverConfig.getProperty(key); String value = OptionConverter.findAndSubst(key, serverConfig); if (NAMES.contains(key)) processENV(key, value); else System.out.println(key + ":" + value); System.setProperty(key, value); } if (System.getProperty("BINDIP") == null && System.getenv("BINDIP") != null) setProperty(ITEMS.BINDIP.name(), System.getenv("BINDIP")); String bindip = getConfig(ITEMS.BINDIP); boolean localhost = bindip.equalsIgnoreCase("localhost"); if (localhost) { try { InetAddress addr = InetAddress.getLocalHost(); bindip = addr.getHostAddress(); setProperty(ITEMS.BINDIP.name(), bindip); System.out.println("BINDIP changed to : " + bindip); String locators = getConfig(ITEMS.LOCATORS); locators = locators.replaceAll("localhost", bindip); setProperty(ITEMS.LOCATORS.name(), locators); System.out.println("LOCATORS changed to : " + locators); } catch (UnknownHostException e) { initlized.set(false); System.err.println("Unkonw host!"); } } processLocators(); // log // PropertyConfigurator.configure(ServerConfigHelper.class.getClassLoader().getResource(log4jFile)); WorkPathHelper.verifyPath("log"); }