List of usage examples for java.net InetAddress getHostName
public String getHostName()
From source file:org.blue.star.plugins.check_ping.java
public boolean execute_check() { for (String hostname : addresses) { try {//from www.j av a 2 s .c o m InetAddress inet = InetAddress.getByName(hostname); long execute_time = 0; long packet_loss = 0; for (int pings = 0; pings < max_packets; pings++) { boolean reachable = false; long ping_time = System.currentTimeMillis(); if (network_interface != null) { reachable = inet.isReachable(network_interface, 0, utils_h.timeout_interval); } else { reachable = inet.isReachable(utils_h.timeout_interval); } execute_time += (System.currentTimeMillis() - ping_time); if (!reachable) packet_loss++; } rta = execute_time / max_packets; pl = (int) packet_loss / max_packets * 100; if (verbose > 0) { System.out.println("rta = " + rta); System.out.println("pl = " + pl); } if (verbose > 1) { System.out.println("isAnyLocalAddress = " + inet.isAnyLocalAddress()); System.out.println("isLinkLocalAddress = " + inet.isLinkLocalAddress()); System.out.println("isLoopbackAddress = " + inet.isLoopbackAddress()); System.out.println("isMCGlobal = " + inet.isMCGlobal()); System.out.println("isMCLinkLocal = " + inet.isMCLinkLocal()); System.out.println("isMCNodeLocal = " + inet.isMCNodeLocal()); System.out.println("isMCOrgLocal = " + inet.isMCOrgLocal()); System.out.println("isMCSiteLocal = " + inet.isMCSiteLocal()); System.out.println("isMulticastAddress = " + inet.isMulticastAddress()); System.out.println("isSiteLocalAddress = " + inet.isSiteLocalAddress()); System.out.println("isReachable = " + inet.isReachable(utils_h.timeout_interval)); System.out.println("getCanonicalHostName = " + inet.getCanonicalHostName()); System.out.println("getHostAddress = " + inet.getHostAddress()); System.out.println("getHostName = " + inet.getHostName()); System.out.println("getClass.getName = " + inet.getClass().getName()); } /* The list is only used to check alternatives, if we pass don't do more */ if (packet_loss != max_packets) break; } catch (Exception e) { warn_text = e.getMessage(); e.printStackTrace(); } } if (pl >= cpl || rta >= crta || rta < 0) check_state = common_h.STATE_CRITICAL; else if (pl >= wpl || rta >= wrta) check_state = common_h.STATE_WARNING; else if (pl >= 0 && rta >= 0) check_state = common_h.STATE_OK; return true; }
From source file:org.opennms.ng.services.capsd.BroadcastEventProcessor.java
/** * This method add a node with the specified node label to the database. If * also adds in interface with the given ipaddress to the node, if the * ipaddr is not null/*from w ww .j ava 2s . com*/ * * @param conn The JDBC Database connection. * @param nodeLabel the node label to identify the node to create. * @param ipaddr the ipaddress to be added into the ipinterface table. * @throws java.sql.SQLException if a database error occurs * @throws org.opennms.netmgt.capsd.FailedOperationException if the ipaddr is not resolvable */ private List<Event> createNodeWithInterface(Connection conn, String nodeLabel, String ipaddr) throws SQLException, FailedOperationException { if (nodeLabel == null) { return Collections.emptyList(); } LOG.debug("addNode: Add a node {} to the database", nodeLabel); List<Event> eventsToSend = new LinkedList<Event>(); DbNodeEntry node = DbNodeEntry.create(); Date now = new Date(); node.setCreationTime(now); node.setNodeType(OnmsNode.NodeType.ACTIVE); node.setLabel(nodeLabel); node.setLabelSource(OnmsNode.NodeLabelSource.USER); node.store(conn); Event newEvent = EventUtils.createNodeAddedEvent(node); eventsToSend.add(newEvent); if (ipaddr != null) { LOG.debug("addNode: Add an IP Address {} to the database", ipaddr); } // add the ipaddess to the database InetAddress ifaddress; try { ifaddress = InetAddressUtils.addr(ipaddr); } catch (final IllegalArgumentException e) { throw new FailedOperationException("unable to resolve host " + ipaddr + ": " + e.getMessage(), e); } DbIpInterfaceEntry ipInterface = DbIpInterfaceEntry.create(node.getNodeId(), ifaddress); ipInterface.setHostname(ifaddress.getHostName()); ipInterface.setManagedState(DbIpInterfaceEntry.STATE_MANAGED); ipInterface.setPrimaryState(DbIpInterfaceEntry.SNMP_NOT_ELIGIBLE); ipInterface.store(conn); Event gainIfEvent = EventUtils.createNodeGainedInterfaceEvent(node, ifaddress); eventsToSend.add(gainIfEvent); return eventsToSend; }
From source file:net.sourceforge.jwebunit.htmlunit.HtmlUnitTestingEngineImpl.java
/** * Initialise the web client before accessing a page. *///from ww w .j a v a 2 s. co m private void initWebClient() { wc = createWebClient(); wc.getOptions().setJavaScriptEnabled(jsEnabled); wc.getOptions().setThrowExceptionOnFailingStatusCode(!ignoreFailingStatusCodes); wc.getOptions().setThrowExceptionOnScriptError(throwExceptionOnScriptError); wc.getOptions().setRedirectEnabled(true); wc.getOptions().setUseInsecureSSL(true); if (refreshHandler == null) { wc.setRefreshHandler(new ImmediateRefreshHandler()); } else { wc.setRefreshHandler(refreshHandler); } wc.getOptions().setTimeout(timeout); DefaultCredentialsProvider creds = new DefaultCredentialsProvider(); if (getTestContext().hasAuthorization()) { creds.addCredentials(getTestContext().getUser(), getTestContext().getPassword()); } if (getTestContext().hasNTLMAuthorization()) { InetAddress netAddress; String address; try { netAddress = InetAddress.getLocalHost(); address = netAddress.getHostName(); } catch (UnknownHostException e) { address = ""; } creds.addNTLMCredentials(getTestContext().getUser(), getTestContext().getPassword(), "", -1, address, getTestContext().getDomain()); } if (getTestContext().hasProxyAuthorization()) { creds.addCredentials(getTestContext().getProxyUser(), getTestContext().getProxyPasswd(), getTestContext().getProxyHost(), getTestContext().getProxyPort(), AuthScope.ANY_REALM); } wc.setCredentialsProvider(creds); wc.addWebWindowListener(new WebWindowListener() { @Override public void webWindowClosed(WebWindowEvent event) { if (win == null || event.getOldPage().equals(win.getEnclosedPage())) { win = wc.getCurrentWindow(); form = null; } String win = event.getWebWindow().getName(); Page oldPage = event.getOldPage(); String oldPageTitle = "no_html"; if (oldPage instanceof HtmlPage) { oldPageTitle = ((HtmlPage) oldPage).getTitleText(); } logger.debug("Window {} closed : {}", win, oldPageTitle); } @Override public void webWindowContentChanged(WebWindowEvent event) { form = null; String winName = event.getWebWindow().getName(); Page oldPage = event.getOldPage(); Page newPage = event.getNewPage(); String oldPageTitle = "no_html"; if (oldPage instanceof HtmlPage) { oldPageTitle = ((HtmlPage) oldPage).getTitleText(); } String newPageTitle = "no_html"; if (newPage instanceof HtmlPage) { newPageTitle = ((HtmlPage) newPage).getTitleText(); } logger.debug("Window \"{}\" changed : \"{}\" became \"{}", new Object[] { winName, oldPageTitle, newPageTitle }); } @Override public void webWindowOpened(WebWindowEvent event) { String win = event.getWebWindow().getName(); Page newPage = event.getNewPage(); if (newPage instanceof HtmlPage) { logger.debug("Window {} opened : {}", win, ((HtmlPage) newPage).getTitleText()); } else { logger.info("Window {} opened", win); } } }); // Add Javascript Alert Handler wc.setAlertHandler(new AlertHandler() { @Override public void handleAlert(Page page, String msg) { if (expectedJavascriptAlerts.size() < 1) { throw new UnexpectedJavascriptAlertException(msg); } else { JavascriptAlert expected = expectedJavascriptAlerts.remove(0); if (!msg.equals(expected.getMessage())) { throw new UnexpectedJavascriptAlertException(msg); } } } }); // Add Javascript Confirm Handler wc.setConfirmHandler(new ConfirmHandler() { @Override public boolean handleConfirm(Page page, String msg) { if (expectedJavascriptConfirms.size() < 1) { throw new UnexpectedJavascriptConfirmException(msg); } else { JavascriptConfirm expected = expectedJavascriptConfirms.remove(0); if (!msg.equals(expected.getMessage())) { throw new UnexpectedJavascriptConfirmException(msg); } else { return expected.getAction(); } } } }); // Add Javascript Prompt Handler wc.setPromptHandler(new PromptHandler() { @Override public String handlePrompt(Page page, String msg) { if (expectedJavascriptPrompts.size() < 1) { throw new UnexpectedJavascriptPromptException(msg); } else { JavascriptPrompt expected = expectedJavascriptPrompts.remove(0); if (!msg.equals(expected.getMessage())) { throw new UnexpectedJavascriptPromptException(msg); } else { return expected.getInput(); } } } }); // Deal with cookies for (javax.servlet.http.Cookie c : getTestContext().getCookies()) { // If Path==null, cookie is not send to the server. wc.getCookieManager().addCookie(new Cookie(c.getDomain() != null ? c.getDomain() : "", c.getName(), c.getValue(), c.getPath() != null ? c.getPath() : "", c.getMaxAge(), c.getSecure())); } // Deal with custom request header Map<String, String> requestHeaders = getTestContext().getRequestHeaders(); for (Map.Entry<String, String> requestHeader : requestHeaders.entrySet()) { wc.addRequestHeader(requestHeader.getKey(), requestHeader.getValue()); } }
From source file:org.opennms.ng.services.capsd.BroadcastEventProcessor.java
/** * Helper method used to create add an interface to a node. * * @param dbConn//from ww w . ja va2s . co m * @param nodeLabel * @param ipaddr * @return a LinkedList of events to be sent * @throws java.sql.SQLException * @throws org.opennms.netmgt.capsd.FailedOperationException */ private List<Event> createInterfaceOnNode(Connection dbConn, String nodeLabel, String ipaddr) throws SQLException, FailedOperationException { PreparedStatement stmt = null; ResultSet rs = null; final DBUtils d = new DBUtils(getClass()); try { // There is no ipinterface associated with the specified nodeLabel // exist in the database. Verify if a node with the nodeLabel already // exist in the database. If not, create a node with the nodeLabel and add it // to the database, and also add the ipaddress associated with this node to // the database. If the node with the nodeLabel exists in the node // table, just add the ip address to the database. stmt = dbConn.prepareStatement(SQL_QUERY_NODE_EXIST); d.watch(stmt); stmt.setString(1, nodeLabel); rs = stmt.executeQuery(); d.watch(rs); List<Event> eventsToSend = new LinkedList<Event>(); while (rs.next()) { LOG.debug("addInterfaceHandler: add interface: {} to the database.", ipaddr); // Node already exists. Add the ipaddess to the ipinterface // table InetAddress ifaddr; try { ifaddr = InetAddressUtils.addr(ipaddr); } catch (final IllegalArgumentException e) { throw new FailedOperationException("unable to resolve host " + ipaddr + ": " + e.getMessage(), e); } int nodeId = rs.getInt(1); String dpName = rs.getString(2); DbIpInterfaceEntry ipInterface = DbIpInterfaceEntry.create(nodeId, ifaddr); ipInterface.setHostname(ifaddr.getHostName()); ipInterface.setManagedState(DbIpInterfaceEntry.STATE_MANAGED); ipInterface.setPrimaryState(DbIpInterfaceEntry.SNMP_NOT_ELIGIBLE); ipInterface.store(dbConn); // create a nodeEntry DbNodeEntry nodeEntry = DbNodeEntry.get(nodeId, dpName); Event newEvent = EventUtils.createNodeGainedInterfaceEvent(nodeEntry, ifaddr); eventsToSend.add(newEvent); } return eventsToSend; } finally { d.cleanUp(); } }
From source file:com.sos.JSHelper.Options.JSOptionsClass.java
/** * * * \brief replaceVars - replace all vars in a string and return the string * * \details/*from w ww . j a va2s.c om*/ * * \return String * */ public String replaceVars(final String pstrReplaceIn) { @SuppressWarnings("unused") final String conMethodName = conClassName + "::replaceVars"; getTextProperties(); try { // zustzliche Parameter generieren objP.put("date", SOSOptionTime.getCurrentDateAsString()); objP.put("time", SOSOptionTime.getCurrentTimeAsString("hh:mm:ss")); objP.put("local_user", System.getProperty("user.name")); java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost(); objP.put("localhost", localMachine.getHostName()); objP.put("local_host_ip", localMachine.getHostAddress()); } catch (Exception uhe) { } String strVal = ""; String strKey = ""; // String strParamNameEnclosedInPercentSigns = ".*%\\{([^%]+)\\}.*"; // %{variableName} String strParamNameEnclosedInPercentSigns = "^.*%\\{([^%]+)\\}.*$"; // String strParamNameEnclosedInPercentSigns2 = "^.*%\\{([^\\}]+).*$"; /** * Problem hier: * Wenn der gesamte String verwendet wird, so ist sptestens beim file_spec * keine korrekte Substitution mehr mglich. * Liegt warscheinlich am regexp pattern. */ String strNewString = ""; if (isNotNull(pstrReplaceIn)) { try { // pstrReplaceIn = pstrReplaceIn.replaceAll("\\n", "\\$\\$N\\$\\$"); String[] strA = pstrReplaceIn.split("\\n"); for (String string : strA) { while (string.matches(strParamNameEnclosedInPercentSigns)) { strKey = string.replaceFirst(strParamNameEnclosedInPercentSigns, "$1"); if (strKey.equalsIgnoreCase("uuid")) { continue; } String strPP = "%\\{" + strKey + "\\}"; strVal = this.OptionByName(strKey); if (isNotNull(strVal)) { strVal = strVal.replace('\\', '/'); string = string.replaceAll(strPP, Matcher.quoteReplacement(strVal)); // logger.debug(Messages.getMsg(JSJ_D_0031, name, strPP, s)); // // "processing job parameter '%1$s': substitute '%2$s' with '%3$s'." } else { strVal = (String) objP.get(strKey); if (strVal != null) { string = string.replaceAll(strPP, Matcher.quoteReplacement(strVal)); } else { strVal = objSettings.get(strKey); if (strVal != null) { string = string.replaceAll(strPP, Matcher.quoteReplacement(strVal)); } else { string = string.replaceAll(strPP, "?" + Matcher.quoteReplacement(strKey) + "?"); // logger.warn(Messages.getMsg(JSJ_D_0032, p)); // "variable '%1$s' not found. no substitution done" } } } } strNewString += string + "\n"; } } catch (Exception e) { // intentionally no error, wrong regexp ? } } // pstrReplaceIn = pstrReplaceIn.replaceAll("\\$\\$N\\$\\$", "\n"); return strNewString; }
From source file:org.apache.hadoop.mapred.RecoverReducerTask.java
/** * recover from schedule log// w ww. j a va2 s .c om */ private void recoverMappersFromScheduleLog() throws IOException, InterruptedException, ClassNotFoundException { FileSystem fs = FileSystem.get(conf); Path path = new Path(MRConstants.SCHEDULE_LOG_DIR + "/" + getJobID().toString() + "/schedule.log"); FSDataInputStream scheduleLog = fs.open(path); mapSchedules.clear(); while (scheduleLog.available() > 0) { MapScheduleInfo msi = new MapScheduleInfo(); msi.readFields(scheduleLog); mapSchedules.add(msi); } scheduleLog.close(); /** * num of maps */ this.numMaps = mapSchedules.size(); InetAddress addr = InetAddress.getLocalHost(); String hostname = addr.getHostName(); List<MapScheduleInfo> recoverMappers = new ArrayList<MapScheduleInfo>(); String httpAddress = conf.get("mapred.task.tracker.http.address"); String[] ipAndPort = httpAddress.split(":"); System.out.println("current host " + hostname); System.out.println("recover for host " + this.getRecoverFromTaskTracker()); if (this.getNodeFailure()) { for (MapScheduleInfo msi : mapSchedules) { /** * find tasktracker to be recovered */ if (msi.getHttpHost().contains(this.getRecoverFromTaskTracker()) || this.getRecoverFromTaskTracker().contains(msi.getHttpHost())) { recoverMappers.add(msi); /** * replace it with a new http address */ msi.setHttpAddress("http://" + hostname + ":" + ipAndPort[1]); // System.out.println("recover from " + msi.getHttpHost()); } } } /** * find latest cached step */ int numSteps = conf.getNumberOfLoopBodySteps(); int cachedIteration = iteration; int cachedStep = step; for (int latest = round; latest >= 0; latest--) { if (cachedStep > 0) { cachedStep--; } else { cachedStep = numSteps - 1; cachedIteration--; } if (loopCacheControl.isCacheWritten(conf, cachedIteration, cachedStep)) break; } this.recoverIteration = cachedIteration; this.recoverStep = cachedStep; this.iteration = recoverIteration; this.step = recoverStep; this.round = recoverIteration * numOfLoopBodySteps + recoverStep; TaskReporter reporter = new TaskReporter(getProgress(), umbilical); reporter.startCommunicationThread(); boolean useNewApi = conf.getUseNewReducer(); /** * set the recovered iteration */ conf.setCurrentIterationAndStep(iteration, step); if (this.getNodeFailure()) { int numConcurrentMappers = 10; JobConf mapConf = conf.duplicate(); mapConf.setInt("io.sort.mb", 100 / numConcurrentMappers); Thread[] mthreads = new Thread[numConcurrentMappers]; int i = 0; int num = recoverMappers.size(); for (i = 0; i < num;) { // execute mappers in batch int j = 0; for (; j < numConcurrentMappers && i < num; j++) { MapScheduleInfo msi = recoverMappers.get(i); MapTask mt = new MapTask(getJobFile(), msi.getTaskAttemptID(), msi.getPartition(), msi.getInputSplit().getClassName(), msi.getInputSplit().getBytes()); // run map task locally to recover mt.setConf(mapConf); mt.setCurrentIteration(iteration); mt.setCurrentStep(step); mt.setRound(); mt.initialize(mapConf, this.getJobID(), reporter, useNewApi); mthreads[j] = new Thread(new MapperRecoverThread(mapConf, umbilical, mt)); mthreads[i].start(); i++; } for (int k = 0; k < j; k++) { Thread thread = mthreads[k]; try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.flush(); System.out.println("recover mappers are finished"); /** * overwrite the scheduling log */ FSDataOutputStream jobLog = fs.create(path); for (MapScheduleInfo msi : mapSchedules) { msi.write(jobLog); } jobLog.close(); System.out.println("recover schedule log are finished"); } }
From source file:com.dragonflow.StandardMonitor.URLOriginalMonitor.java
/** * // www . j av a2s.c o m * */ public String getHostname() { String s; s = HTTPUtils.hostFromURL(getProperty(pURL)); if (getSetting("_urlLookupHost").length() > 0) { try { InetAddress inetaddress = InetAddress.getByName(s); String s1 = inetaddress.getHostAddress(); InetAddress inetaddress1 = InetAddress.getByName(s1); return inetaddress1.getHostName(); } catch (Exception e) { LogManager.log("Error", "Failed to perform reverse lookup " + e); return s; } } return s; }
From source file:org.ramadda.repository.Repository.java
/** * _more_/* www. jav a 2 s . c om*/ * * @param args _more_ * @param port _more_ * * @throws Exception _more_ */ public void init(String[] args, int port) throws Exception { setPort(port); LogUtil.setTestMode(true); try { java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost(); setHostname(localMachine.getHostName()); setIpAddress(localMachine.getHostAddress()); } catch (Exception exc) { System.err.println("Got exception accessing local hostname"); exc.printStackTrace(); setHostname("unknown"); setIpAddress("unknown"); } this.args = args; entryEditUrls = RepositoryUtil.toList(new RequestUrl[] { URL_ENTRY_FORM, URL_ENTRY_WALK, getMetadataManager().URL_METADATA_FORM, getMetadataManager().URL_METADATA_ADDFORM, URL_ACCESS_FORM //, // URL_ENTRY_DELETE // URL_ENTRY_SHOW }); groupEditUrls = RepositoryUtil.toList(new RequestUrl[] { URL_ENTRY_NEW, URL_ENTRY_FORM, URL_ENTRY_WALK, getMetadataManager().URL_METADATA_FORM, getMetadataManager().URL_METADATA_ADDFORM, URL_ACCESS_FORM //, // URL_ENTRY_DELETE // URL_ENTRY_SHOW }); }
From source file:jhttpp2.Jhttpp2HTTPSession.java
/** the main routine, where it all happens */ public void handleRequest() throws Exception { InetAddress remote_host; Jhttpp2Read remote_in = null;// w ww . j a va 2s . c o m int remote_port; byte[] b = new byte[65536]; int numread = in.read(b); while (true) { // with this loop we support persistent connections if (numread == -1) { // -1 signals an error if (in.getStatusCode() != SC_CONNECTING_TO_HOST) { switch (in.getStatusCode()) { case SC_CONNECTION_CLOSED: break; case SC_CLIENT_ERROR: sendErrorMSG(400, "Your client sent a request that this proxy could not understand. (" + in.getErrorDescription() + ")"); break; case SC_HOST_NOT_FOUND: sendErrorMSG(504, "Host not found.<BR>jHTTPp2 was unable to resolve the hostname of this request. <BR>Perhaps the hostname was misspelled, the server is down or you have no connection to the internet."); break; case SC_INTERNAL_SERVER_ERROR: sendErrorMSG(500, "Server Error! (" + in.getErrorDescription() + ")"); break; case SC_NOT_SUPPORTED: sendErrorMSG(501, "Your client used a HTTP method that this proxy doesn't support: (" + in.getErrorDescription() + ")"); break; case SC_URL_BLOCKED: sendErrorMSG(403, (in.getErrorDescription() != null && in.getErrorDescription().length() > 0 ? in.getErrorDescription() : "The request for this URL was denied by the jHTTPp2 URL-Filter.")); break; // case SC_REMOTE_DEBUG_MODE: remoteDebug(); break; case SC_HTTP_OPTIONS_THIS: sendHeader(200); endHeader(); break; case SC_FILE_REQUEST: file_handler(); break; case SC_CONFIG_RQ: admin_handler(b); break; // case SC_HTTP_TRACE: case SC_MOVED_PERMANENTLY: sendHeader(301); write(out, "Location: " + in.getErrorDescription() + "\r\n"); endHeader(); out.flush(); default: } break; // return from main loop. } else { // also an error because we are not connected (or to // the wrong host) // Creates a new connection to a remote host. if (!notConnected()) { try { HTTP_Socket.close(); } catch (IOException e_close_socket) { } } numread = in.getHeaderLength(); // get the header length if (!server.use_proxy) {// sets up hostname and port remote_host = in.getRemoteHost(); remote_port = in.remote_port; } else { remote_host = server.proxy; remote_port = server.proxy_port; } // if (server.debug)server.writeLog("Connect: " + // remote_host + ":" + remote_port); try { connect(remote_host, remote_port); } catch (IOException e_connect) { if (server.debug) server.writeLog(e_connect.toString()); sendErrorMSG(502, "Error while creating a TCP connecting to [" + remote_host.getHostName() + ":" + remote_port + "] <BR>The proxy server cannot connect to the given address or port [" + e_connect.toString() + "]"); break; } catch (Exception e) { server.writeLog(e.toString()); sendErrorMSG(500, "Error: " + e.toString()); break; } if (!in.isTunnel() || (in.isTunnel() && server.use_proxy)) { // no // SSL-Tunnel // or // SSL-Tunnel // with // another // remote // proxy: // simply // forward // the // request HTTP_out.write(b, 0, numread); HTTP_out.flush(); } else { // SSL-Tunnel with "CONNECT": creates a tunnel // connection with the server sendLine(server.getHttpVersion() + " 200 Connection established"); sendLine("Proxy-Agent", server.getServerIdentification()); endHeader(); out.flush(); } remote_in = new Jhttpp2Read(server, this, HTTP_in, out); // reads // data // from // the // remote // server server.addBytesWritten(numread); } } while (true) { // reads data from the client numread = in.read(b); // if (server.debug)server.writeLog("Jhttpp2HTTPSession: " + // numread + " Bytes read."); if (numread != -1) { HTTP_out.write(b, 0, numread); HTTP_out.flush(); server.addBytesWritten(numread); } else break; } // end of inner loop } // end of main loop out.flush(); if (!notConnected() && remote_in != null) remote_in.close(); // close Jhttpp2Read thread return; }
From source file:rems.Global.java
public static String[] getMachDetails() { System.setProperty("java.net.preferIPv4Stack", "true"); String[] nameIP = new String[3]; nameIP[0] = ""; nameIP[1] = ""; nameIP[2] = ""; InetAddress ip; String hostname;//from w ww . jav a2s . c o m try { ip = InetAddress.getLocalHost(); /*Enumeration e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface n = (NetworkInterface) e.nextElement(); // if (n.isLoopback() || n.isVirtual() || !n.isUp()) { } else if (n.isUp()) { Enumeration ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); //System.out.println(i.getHostAddress()); //nameIP[2] = i.getHostAddress(); ip = i; //break; } //break; } }*/ nameIP[2] = ip.getHostAddress(); hostname = ip.getHostName(); nameIP[0] = hostname; //System.out.println("Current IP address : " + ip.getHostAddress()); NetworkInterface network = NetworkInterface.getByInetAddress(ip); byte[] mac = network.getHardwareAddress(); //System.out.print("Current MAC address : "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < mac.length; i++) { sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); } //System.out.println(sb.toString()); nameIP[1] = sb.toString(); return nameIP; } catch (SocketException e) { return nameIP; } catch (UnknownHostException ex) { return nameIP; } catch (Exception ex) { return nameIP; } }