List of usage examples for java.net InetAddress getHostName
public String getHostName()
From source file:org.trafodion.rest.zookeeper.ZkQuorumPeer.java
static void writeMyID(Properties properties) throws IOException { long myId = -1; Configuration conf = RestConfiguration.create(); String myAddress = Strings//from w ww.jav a 2 s . c o m .domainNamePointerToHostName(DNS.getDefaultHost(conf.get("rest.zookeeper.dns.interface", "default"), conf.get("rest.zookeeper.dns.nameserver", "default"))); List<String> ips = new ArrayList<String>(); // Add what could be the best (configured) match ips.add(myAddress.contains(".") ? myAddress : StringUtils.simpleHostname(myAddress)); // For all nics get all hostnames and IPs Enumeration<?> nics = NetworkInterface.getNetworkInterfaces(); while (nics.hasMoreElements()) { Enumeration<?> rawAdrs = ((NetworkInterface) nics.nextElement()).getInetAddresses(); while (rawAdrs.hasMoreElements()) { InetAddress inet = (InetAddress) rawAdrs.nextElement(); ips.add(StringUtils.simpleHostname(inet.getHostName())); ips.add(inet.getHostAddress()); } } for (Entry<Object, Object> entry : properties.entrySet()) { String key = entry.getKey().toString().trim(); String value = entry.getValue().toString().trim(); if (key.startsWith("server.")) { int dot = key.indexOf('.'); long id = Long.parseLong(key.substring(dot + 1)); String[] parts = value.split(":"); String address = parts[0]; if (addressIsLocalHost(address) || ips.contains(address)) { myId = id; break; } } } // Set the max session timeout from the provided client-side timeout properties.setProperty("maxSessionTimeout", conf.get("zookeeper.session.timeout", "180000")); if (myId == -1) { throw new IOException( "Could not find my address: " + myAddress + " in list of ZooKeeper quorum servers"); } String dataDirStr = properties.get("dataDir").toString().trim(); File dataDir = new File(dataDirStr); if (!dataDir.isDirectory()) { if (!dataDir.mkdirs()) { throw new IOException("Unable to create data dir " + dataDir); } } File myIdFile = new File(dataDir, "myid"); PrintWriter w = new PrintWriter(myIdFile); w.println(myId); w.close(); }
From source file:org.apache.eagle.topology.utils.EntityBuilderHelper.java
public static String resolveHostByIp(String ip) { InetAddress addr = null; try {/* www. j av a2s.co m*/ addr = InetAddress.getByName(ip); } catch (UnknownHostException e) { e.printStackTrace(); } return addr.getHostName(); }
From source file:ntpgraphic.LineChart.java
public static void NTPClient(String[] servers, int i) { Properties defaultProps = System.getProperties(); //obtiene las "properties" del sistema defaultProps.put("java.net.preferIPv6Addresses", "true");//mapea el valor true en la variable java.net.preferIPv6Addresses if (servers.length == 0) { System.err.println("Usage: NTPClient <hostname-or-address-list>"); System.exit(1);/*from w ww . j ava 2s .co m*/ } Promedio = 0; Cant = 0; NTPUDPClient client = new NTPUDPClient(); // We want to timeout if a response takes longer than 10 seconds client.setDefaultTimeout(10000); try { client.open(); for (String arg : servers) { System.out.println(); try { InetAddress hostAddr = InetAddress.getByName(arg); System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress()); TimeInfo info = client.getTime(hostAddr); processResponse(info, i); } catch (IOException ioe) { System.err.println(ioe.toString()); } } } catch (SocketException e) { System.err.println(e.toString()); } client.close(); //System.out.println("\n Pomedio "+(Promedio/Cant)); }
From source file:org.apache.axis.utils.NetworkUtils.java
/** * Get the string defining the hostname of the system, as taken from * the default network adapter of the system. There is no guarantee that * this will be fully qualified, or that it is the hostname used by external * machines to access the server.//from w w w . ja v a2 s. c o m * If we cannot determine the name, then we return the default hostname, * which is defined by {@link #LOCALHOST} * @return a string name of the host. */ public static String getLocalHostname() { InetAddress address; String hostname; try { address = InetAddress.getLocalHost(); //force a best effort reverse DNS lookup hostname = address.getHostName(); if (hostname == null || hostname.length() == 0) { hostname = address.toString(); } } catch (UnknownHostException noIpAddrException) { //this machine is not on a LAN, or DNS is unhappy //return the default hostname if (log.isDebugEnabled()) { log.debug("Failed to lookup local IP address", noIpAddrException); } hostname = LOCALHOST; } return hostname; }
From source file:Main.java
protected static void obtainHostInfo() { HOST_IPADDRESS = "127.0.0.1"; HOST_NAME = ""; try {//from w w w . j a v a2 s . c o m InetAddress primera = InetAddress.getLocalHost(); String hostname = InetAddress.getLocalHost().getHostName(); if (!primera.isLoopbackAddress() && !primera.getHostName().equalsIgnoreCase("localhost") && primera.getHostAddress().indexOf(':') == -1) { // Get it without delay!! //System.out.println ("we have it!"); HOST_IPADDRESS = primera.getHostAddress(); HOST_NAME = hostname; //System.out.println (hostname + " IP " + HOST_IPADDRESS); return; } // Get it by slow way ... InetAddress[] familia = InetAddress.getAllByName(hostname); int netto = 1; for (int aa = 0; aa < familia.length; aa++) { // System.out.println ("Networko " + netto++); InetAddress laAdd = familia[aa]; String ipstring = laAdd.getHostAddress(); hostname = laAdd.getHostName(); // don't know if it can change, probably not // System.out.println ("checking : " + hostname + " IP " + ipstring); if (laAdd.isLoopbackAddress()) continue; if (hostname.equalsIgnoreCase("localhost")) continue; if (ipstring.indexOf(':') >= 0) continue; // System.out.println ("this pass!"); HOST_IPADDRESS = ipstring; HOST_NAME = hostname; break; } } catch (Exception e) { } }
From source file:org.hillview.utils.Utilities.java
/** * Gets the name of the local machine./* www .j av a2s . co m*/ */ public static String getHostName() { try { java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost(); return localMachine.getHostName(); } catch (java.net.UnknownHostException e) { HillviewLogger.instance.error("Cannot get host name"); return "?"; } }
From source file:amplify.NTPClient.java
public static void syncServerTime(String ntpServerAddress) throws IOException { NTPUDPClient client = new NTPUDPClient(); // We want to timeout if a response takes longer than 10 seconds client.setDefaultTimeout(10000);//from w w w .j a va 2 s . c o m try { client.open(); System.out.println(); try { InetAddress hostAddr = InetAddress.getByName(ntpServerAddress); System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress()); TimeInfo info = client.getTime(hostAddr); processResponse(info); } catch (IOException ioe) { client.close(); throw ioe; } } catch (SocketException e) { client.close(); throw e; } client.close(); }
From source file:ca.uoguelph.ccs.portal.services.feedback.web.FeedbackFormController.java
public static String getPortalServerName() { String portalHostName = "Undefined"; try {/* w ww .ja va2s .com*/ java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost(); String hostname = localMachine.getHostName(); /*coded host names for the production portal "P?" coded host names for the qa portal "QA?" */ //hostname = (String) request.getServerName(); //for domain name qa.myportico.uoguelph.ca System.out.println("hostname: " + hostname); if ("happy".equalsIgnoreCase(hostname)) { portalHostName = "P1"; } else if ("doc".equalsIgnoreCase(hostname)) { portalHostName = "P2"; } else if ("bashful".equalsIgnoreCase(hostname)) { portalHostName = "P3"; } else if ("sneezy".equalsIgnoreCase(hostname)) { portalHostName = "P4"; //} else if ("grumpy".equals(hostname)) { //given out to forums herbie.cs.uoguelph.ca } else if ("herbie.cs.uoguelph.ca".equalsIgnoreCase(hostname) || "herbie".equalsIgnoreCase(hostname)) { portalHostName = "P5"; } else if ("sleepy".equalsIgnoreCase(hostname)) { portalHostName = "QA1"; } else if ("dopey".equalsIgnoreCase(hostname)) { portalHostName = "QA2"; } else if ("snowwhite".equalsIgnoreCase(hostname)) { portalHostName = "L1"; } else if ("prince".equalsIgnoreCase(hostname)) { portalHostName = "L2"; } } catch (java.net.UnknownHostException uhe) { } return portalHostName; }
From source file:com.nridge.core.base.std.Platform.java
/** * Convenience method that returns the host name of the current machine. * * @return Host name.// w w w . ja v a2s . co m */ public static String getHostName() { String hostName; try { InetAddress inetAddress = InetAddress.getLocalHost(); hostName = inetAddress.getHostName(); } catch (UnknownHostException e) { hostName = "localhost"; } return hostName; }
From source file:NTP_Example.java
/** * Process <code>TimeInfo</code> object and print its details. * @param info <code>TimeInfo</code> object. *//*from w w w .j a va 2 s . c o 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 + ")"; } 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 }