List of usage examples for java.net InetAddress getByName
public static InetAddress getByName(String host) throws UnknownHostException
From source file:com.alibaba.jstorm.utils.NetWorkUtils.java
public static String ip2Host(String ip) { InetAddress address = null;/* w w w .ja va2 s .c o m*/ try { address = InetAddress.getByName(ip); } catch (UnknownHostException e) { LOG.warn("NetWorkUtil can't transfer ip(" + ip + ") to hostname, return ip", e); return ip; } return address.getHostName(); }
From source file:beans.NTPClient.java
/** * Process <code>TimeInfo</code> object and print its details. * /* w ww .ja v a 2 s . c o m*/ * @param info * <code>TimeInfo</code> object. */ public static void processResponse(TimeInfo info) { NtpV3Packet message = info.getMessage(); int stratum = message.getStratum(); String refType; if (stratum <= 0) { refType = "(Unspecified or Unavailable)"; } else if (stratum == 1) { refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock, etc. } else { refType = "(Secondary Reference; e.g. via NTP or SNTP)"; } // stratum should be 0..15... System.out.println(" Stratum: " + stratum + " " + refType); int version = message.getVersion(); int li = message.getLeapIndicator(); System.out.println(" leap=" + li + ", version=" + version + ", precision=" + message.getPrecision()); System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")"); int poll = message.getPoll(); // poll value typically btwn MINPOLL (4) and MAXPOLL (14) System.out.println( " poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll)) + " seconds" + " (2 ** " + poll + ")"); double disp = message.getRootDispersionInMillisDouble(); System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble()) + ", rootdispersion(ms): " + numberFormat.format(disp)); int refId = message.getReferenceId(); String refAddr = NtpUtils.getHostAddress(refId); String refName = null; if (refId != 0) { if (refAddr.equals("127.127.1.0")) { refName = "LOCAL"; // This is the ref address for the Local Clock } else if (stratum >= 2) { // If reference id has 127.127 prefix then it uses its own reference // clock // defined in the form 127.127.clock-type.unit-num (e.g. 127.127.8.0 // mode 5 // for GENERIC DCF77 AM; see refclock.htm from the NTP software // distribution. if (!refAddr.startsWith("127.127")) { try { InetAddress addr = InetAddress.getByName(refAddr); String name = addr.getHostName(); if (name != null && !name.equals(refAddr)) { refName = name; } } catch (UnknownHostException e) { // some stratum-2 servers sync to ref clock device but fudge stratum // level higher... (e.g. 2) // ref not valid host maybe it's a reference clock name? // otherwise just show the ref IP address. refName = NtpUtils.getReferenceClock(message); } } } else if (version >= 3 && (stratum == 0 || stratum == 1)) { refName = NtpUtils.getReferenceClock(message); // refname usually have at least 3 characters (e.g. GPS, WWV, LCL, etc.) } // otherwise give up on naming the beast... } if (refName != null && refName.length() > 1) { refAddr += " (" + refName + ")"; } System.out.println(" Reference Identifier:\t" + refAddr); TimeStamp refNtpTime = message.getReferenceTimeStamp(); System.out.println(" Reference Timestamp:\t" + refNtpTime + " " + refNtpTime.toDateString()); // Originate Time is time request sent by client (t1) TimeStamp origNtpTime = message.getOriginateTimeStamp(); System.out.println(" Originate Timestamp:\t" + origNtpTime + " " + origNtpTime.toDateString()); long destTime = info.getReturnTime(); // Receive Time is time request received by server (t2) TimeStamp rcvNtpTime = message.getReceiveTimeStamp(); System.out.println(" Receive Timestamp:\t" + rcvNtpTime + " " + rcvNtpTime.toDateString()); // Transmit time is time reply sent by server (t3) TimeStamp xmitNtpTime = message.getTransmitTimeStamp(); System.out.println(" Transmit Timestamp:\t" + xmitNtpTime + " " + xmitNtpTime.toDateString()); // Destination time is time reply received by client (t4) TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime); System.out.println(" Destination Timestamp:\t" + destNtpTime + " " + destNtpTime.toDateString()); info.computeDetails(); // compute offset/delay if not already done Long offsetValue = info.getOffset(); Long delayValue = info.getDelay(); String delay = (delayValue == null) ? "N/A" : delayValue.toString(); String offset = (offsetValue == null) ? "N/A" : offsetValue.toString(); System.out.println(" Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset); // offset // in // ms }
From source file:com.amplify.gcm.hack.NTPClient.java
/** * Process <code>TimeInfo</code> object and print its details. * * @param info <code>TimeInfo</code> object. */// w w w. j a v a 2 s. co m public static void processResponse(TimeInfo info) { NtpV3Packet message = info.getMessage(); int stratum = message.getStratum(); String refType; if (stratum <= 0) refType = "(Unspecified or Unavailable)"; else if (stratum == 1) refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock, etc. else refType = "(Secondary Reference; e.g. via NTP or SNTP)"; // stratum should be 0..15... System.out.println(" Stratum: " + stratum + " " + refType); int version = message.getVersion(); int li = message.getLeapIndicator(); System.out.println(" leap=" + li + ", version=" + version + ", precision=" + message.getPrecision()); System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")"); int poll = message.getPoll(); // poll value typically btwn MINPOLL (4) and MAXPOLL (14) System.out.println( " poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll)) + " seconds" + " (2 ** " + poll + ")"); double disp = message.getRootDispersionInMillisDouble(); System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble()) + ", rootdispersion(ms): " + numberFormat.format(disp)); int refId = message.getReferenceId(); String refAddr = NtpUtils.getHostAddress(refId); String refName = null; if (refId != 0) { if (refAddr.equals("127.127.1.0")) { refName = "LOCAL"; // This is the ref address for the Local Clock } else if (stratum >= 2) { // If reference id has 127.127 prefix then it uses its own reference clock // defined in the form 127.127.clock-type.unit-num (e.g. 127.127.8.0 mode 5 // for GENERIC DCF77 AM; see refclock.htm from the NTP software distribution. if (!refAddr.startsWith("127.127")) { try { InetAddress addr = InetAddress.getByName(refAddr); String name = addr.getHostName(); if (name != null && !name.equals(refAddr)) refName = name; } catch (UnknownHostException e) { // some stratum-2 servers sync to ref clock device but fudge stratum level higher... (e.g. 2) // ref not valid host maybe it's a reference clock name? // otherwise just show the ref IP address. refName = NtpUtils.getReferenceClock(message); } } } else if (version >= 3 && (stratum == 0 || stratum == 1)) { refName = NtpUtils.getReferenceClock(message); // refname usually have at least 3 characters (e.g. GPS, WWV, LCL, etc.) } // otherwise give up on naming the beast... } if (refName != null && refName.length() > 1) refAddr += " (" + refName + ")"; TimeStamp refNtpTime = message.getReferenceTimeStamp(); // Originate Time is time request sent by client (t1) TimeStamp origNtpTime = message.getOriginateTimeStamp(); long destTime = info.getReturnTime(); long localDestTime = System.currentTimeMillis(); // Receive Time is time request received by server (t2) TimeStamp rcvNtpTime = message.getReceiveTimeStamp(); // Transmit time is time reply sent by server (t3) TimeStamp xmitNtpTime = message.getTransmitTimeStamp(); // Destination time is time reply received by client (t4) TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime); info.computeDetails(); // compute offset/delay if not already done Long offsetValue = info.getOffset(); Long delayValue = info.getDelay(); String delay = (delayValue == null) ? "N/A" : delayValue.toString(); String offset = (offsetValue == null) ? "N/A" : offsetValue.toString(); clockOffset = offsetValue != null ? offsetValue.longValue() : 0L; Log.i(TAG, " Reference Identifier:\t" + refAddr); Log.i(TAG, " Reference Timestamp:\t" + refNtpTime + " " + refNtpTime.toDateString()); Log.i(TAG, " Originate Timestamp:\t" + origNtpTime + " " + origNtpTime.toDateString()); Log.i(TAG, " Receive Timestamp:\t" + rcvNtpTime + " " + rcvNtpTime.toDateString()); Log.i(TAG, " Transmit Timestamp:\t" + xmitNtpTime + " " + xmitNtpTime.toDateString()); Log.i(TAG, " Destination Timestamp:\t" + destNtpTime + " " + destNtpTime.toDateString()); Log.i(TAG, " Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset); }
From source file:de.undercouch.gradle.tasks.download.TestBase.java
/** * Gets the local host name to use for the tests * @throws UnknownHostException if the local host name could not be * resolved into an address//from w ww .j ava 2 s .co m * @throws SocketException if an I/O error occurs */ @BeforeClass public static void setUpClass() throws UnknownHostException, SocketException { try { InetAddress.getByName("localhost.localdomain"); localHostName = "localhost.localdomain"; } catch (UnknownHostException e) { localHostName = findSiteLocal(); if (localHostName == null) { localHostName = InetAddress.getLocalHost().getCanonicalHostName(); } } }
From source file:com.pavlovmedia.oss.osgi.gelf.impl.GelfLogSink.java
private synchronized void ensureConnection() { if (null == transport) { try {/* w w w .j a va 2 s .c o m*/ InetAddress address = InetAddress.getByName(hostname); transport = new Socket(address, port); transport.shutdownInput(); readerService.addLogListener(this); } catch (IOException e) { if (consoleMessages) { System.err.println( String.format("Failed to connect to %s:%d => %s", hostname, port, e.getMessage())); e.printStackTrace(); } transport = null; } } }
From source file:com.impetus.ankush.common.utils.NmapUtil.java
/** * Gets the node list with status.// ww w . j a v a 2 s .c o m * * @return the node list with status */ public Map<String, Boolean> getNodeListWithStatus() { // create result hash map. Map<String, Boolean> result = new HashMap<String, Boolean>(); if ((nodePattern != null) && !nodePattern.isEmpty() && !nodePattern.equals(Constant.Strings.SPACE)) { // split the nodePattern on Comma String[] splittedNodeArray = this.nodePattern.split(Constant.Strings.SPACE); Boolean isReachable = false; for (String host : splittedNodeArray) { try { isReachable = InetAddress.getByName(host.trim()).isReachable(3000); result.put(host.trim(), isReachable); } catch (Exception e) { logger.error(e.getMessage(), e); } } } return result; }
From source file:com.blockwithme.time.internal.NTPClockSynchronizer.java
@Override public long getLocalToUTCTimeOffset() throws Exception { final NTPUDPClient client = new NTPUDPClient(); // final Calendar cal = Calendar.getInstance(DEFAULT_LOCAL); // We want to timeout if a response takes longer than 3 seconds client.setDefaultTimeout(TIMEOUT); long offsetSum = 0L; int offsetCount = 0; long bestDelay = Long.MAX_VALUE; long bestOffset = Long.MAX_VALUE; Throwable lastException = null; try {//from ww w . j a v a 2s . c om client.open(); for (int i = 0; i < ntpPool.length; i++) { try { final InetAddress hostAddr = InetAddress.getByName(ntpPool[i]); final TimeInfo info = client.getTime(hostAddr); info.computeDetails(); final Long offsetValue = info.getOffset(); final Long delayValue = info.getDelay(); if ((delayValue != null) && (offsetValue != null)) { // cal.setTimeInMillis(offsetValue // + System.currentTimeMillis()); // final long local2UTC = -(cal.get(Calendar.ZONE_OFFSET) + cal // .get(Calendar.DST_OFFSET)); if (delayValue <= 100L) { offsetSum += offsetValue;// + local2UTC; offsetCount++; } if (delayValue < bestDelay) { bestDelay = delayValue; bestOffset = offsetValue;// + local2UTC; } } } catch (final Throwable t) { LOG.error("Error reading tiem through NTP", t); lastException = t; } } } catch (final Throwable t) { LOG.error("Error reading tiem through NTP", t); lastException = t; // NTPUDPClient can't even open at all!?! } finally { client.close(); } if (offsetCount > 0) { return offsetSum / offsetCount; } // OK, not good result. Any result at all? if (bestDelay != Long.MAX_VALUE) { return bestOffset; } // FAIL! throw new Exception("Failed to get NTP time", lastException); }
From source file:org.elasticsoftware.elasticactors.configuration.NodeConfiguration.java
@PostConstruct public void init() throws IOException { // get the yaml resource Resource configResource = resourceLoader .getResource(env.getProperty("ea.node.config.location", "classpath:ea-default.yaml")); // yaml mapper ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); configuration = objectMapper.readValue(configResource.getInputStream(), DefaultConfiguration.class); String nodeId = env.getRequiredProperty("ea.node.id"); InetAddress nodeAddress = InetAddress.getByName(env.getRequiredProperty("ea.node.address")); String clusterName = env.getRequiredProperty("ea.cluster"); node = new ElasticActorsNode(clusterName, nodeId, nodeAddress, configuration); }
From source file:de.upb.wdqa.wdvd.geolocation.GeolocationDatabase.java
public static GeoInformation getGeoInformation(String str) { GeoInformation result = null;/*from w w w .ja v a2 s. c o m*/ try { InetAddress adress = InetAddress.getByName(str); byte[] bytes = adress.getAddress(); ArrayUtils.reverse(bytes); BigInteger bigInt = new BigInteger(1, adress.getAddress()); long longAdress = bigInt.longValue(); result = getGeoInformation(longAdress); } catch (UnknownHostException e) { logger.error("IP Adress not known: " + str); } return result; }
From source file:org.transdroid.util.TlsSniSocketFactory.java
@Override @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException { if (autoClose) { // we don't need the plainSocket plainSocket.close();/*from w w w . jav a2 s . c om*/ } SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory .getDefault(0); // create and connect SSL socket, but don't do hostname/certificate verification yet SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port); // enable TLSv1.1/1.2 if available ssl.setEnabledProtocols(ssl.getSupportedProtocols()); // set up SNI before the handshake if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { sslSocketFactory.setHostname(ssl, host); } else { try { java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class); setHostnameMethod.invoke(ssl, host); } catch (Exception e) { Log.d(TlsSniSocketFactory.class.getSimpleName(), "SNI not usable: " + e); } } // verify hostname and certificate SSLSession session = ssl.getSession(); if (!hostnameVerifier.verify(host, session)) { throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host); } return ssl; }