List of usage examples for java.net InetAddress getHostAddress
public String getHostAddress()
From source file:uk.org.openseizuredetector.MainActivity.java
/** get the ip address of the phone. * Based on http://stackoverflow.com/questions/11015912/how-do-i-get-ip-address-in-ipv4-format *//*ww w.j a v a 2 s . c o m*/ public String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); //Log.v(TAG,"ip1--:" + inetAddress); //Log.v(TAG,"ip2--:" + inetAddress.getHostAddress()); // for getting IPV4 format if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) { String ip = inetAddress.getHostAddress().toString(); //Log.v(TAG,"ip---::" + ip); return ip; } } } } catch (Exception ex) { Log.e("IP Address", ex.toString()); } return null; }
From source file:com.stimulus.archiva.incoming.IAPRunnable.java
public void run() { try {//from ww w . ja v a2s. c o m java.net.InetAddress inetAdd = java.net.InetAddress.getByName(connection.getServerName()); ipAddress = inetAdd.getHostAddress(); } catch (UnknownHostException uhe) { logger.debug("failed to resolve address of mail server {connection.getServerName()='" + connection.getServerName() + "',port='" + connection.getPort() + "',userName='" + connection.getUsername() + ",protocol='" + connection.getProtocol() + "'}"); testOutput("failed to resolve ip address of mail server " + connection.getServerName()); } if (ipAddress == null) { ipAddress = "unknown"; } shutdown = false; while (!shutdown) { MAX_MESSAGES_TO_PROCESS = Config.getConfig().getMailboxConnections().getMaxMessages(); logger.debug("connecting to mail server {serverName='" + connection.getServerName() + "',port='" + connection.getPort() + "',userName='" + connection.getUsername() + ",protocol='" + connection.getProtocol() + "'}"); testOutput("connecting to mail server " + connection.getServerName()); try { connect(); } catch (Throwable e) { logger.error("failed to connect to mail server {serverName='" + connection.getServerName() + "',port='" + connection.getPort() + "',userName='" + connection.getUsername() + "',protocol='" + connection.getProtocol() + "'}. will retry in 1 second.", e); if (e.getCause() instanceof AuthenticationFailedException) testOutput("could not authenticate with mail server " + connection.getServerName() + ". username and/or password incorrect?"); else { String errormessage = ""; if (e.getCause() != null && e.getCause().getMessage() != null) errormessage = e.getCause().getMessage(); testOutput("failed to connect to mail server " + connection.getServerName() + ". " + e.getMessage() + "[" + errormessage + "]"); } if (testCallback != null) { break; } else { try { disconnect(); } catch (Exception ed) { } try { Thread.sleep(intervalSecs); } catch (Exception e2) { } continue; } } logger.debug("connected to mail server {serverName='" + connection.getServerName() + "',port='" + connection.getPort() + "',userName='" + connection.getUsername() + "'}"); testOutput("connected to mail server " + connection.getServerName()); if (testCallback == null) { if (Compare.equalsIgnoreCase(connection.getProtocol().toString(), "IMAP") && connection.getIdle()) { imapIdleMessages(); logger.debug("imap idle messages return()"); } else { pollMessages(); } } try { disconnect(); } catch (Exception e) { logger.error("failed to disconnect from mail server:" + e.getMessage() + "{ serverName='" + connection.getServerName() + "',port='" + connection.getPort() + "',userName='" + connection.getUsername() + "'}", e); testOutput("failed to disconnect from mail server " + connection.getServerName()); } catch (Throwable t) { logger.error("failed to disconnect from mail server:" + t.getMessage() + "{ serverName='" + connection.getServerName() + "',port='" + connection.getPort() + "',userName='" + connection.getUsername() + "'}", t); testOutput("failed to disconnect from mail server " + connection.getServerName()); } if (testCallback == null && !(connection.getProtocol() == MailboxConnections.Protocol.IMAP && connection.getIdle())) { logger.debug("iap sleep {time='" + (intervalSecs * 1000) + "'}"); try { Thread.sleep(intervalSecs * 1000); } catch (Exception e) { } } if (testCallback != null) { testOutput("test complete."); break; } } if (testCallback == null && logger != null) { logger.warn("the iap service is shutdown {shutdown='" + shutdown + "'}"); } }
From source file:com.att.android.arodatacollector.utils.AROCollectorUtils.java
/** * Returns the IP Address of the device during the trace cycle when it is * connected to the network./*from ww w . ja v a 2 s .com*/ * * @return The IP Address of the device. * * @throws java.net.SocketException */ public String getLocalIpAddress() throws SocketException { for (final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { final NetworkInterface intf = en.nextElement(); for (final Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { final InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress(); } } } return null; }
From source file:org.deviceconnect.android.deviceplugin.chromecast.profile.ChromeCastMediaPlayerProfile.java
/** * IP??/* w w w .j a v a 2 s.c o m*/ * * @param ?? * @return IP */ private String getIpAddress() { try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement(); Enumeration<InetAddress> ipAddrs = networkInterface.getInetAddresses(); while (ipAddrs.hasMoreElements()) { InetAddress ip = (InetAddress) ipAddrs.nextElement(); String ipStr = ip.getHostAddress(); if (!ip.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipStr)) { return ipStr; } } } } catch (SocketException e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } } return null; }
From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java
public String getLocalIpAddress() { try {/*from w ww .j a v a 2s .c o m*/ InetAddress inetAddress = getLocalInetAddress(); if (inetAddress != null) return inetAddress.getHostAddress().toString(); } catch (SocketException ex) { Toast.makeText(getApplication().getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); } return null; }
From source file:com.tresys.jalop.utils.jnltest.SubscriberImpl.java
/** * Create a {@link SubscriberImpl} object. Instances of this class will * create sub-directories under <code>outputIpRoot</code> for each downloaded * record.// www. ja v a2 s .c o m * * @param recordType * The type of record that will be transfered using this instance. * @param outputRoot * The output directory that records will be written to. * @param remoteAddr * The {@link InetAddress} of the remote. */ public SubscriberImpl(final RecordType recordType, final File outputRoot, final InetAddress remoteAddr, final JNLTest jnlTest) { this.recordType = recordType; this.remoteIp = remoteAddr.getHostAddress(); this.jnlTest = jnlTest; final File tmp = new File(outputRoot, remoteAddr.getHostAddress()); final String type; switch (recordType) { case Audit: type = "audit"; break; case Journal: type = "journal"; break; case Log: type = "log"; break; default: throw new IllegalArgumentException("illegal record type"); } this.outputRoot = new File(outputRoot, type); if (!this.outputRoot.exists()) { this.outputRoot.mkdirs(); } if (!(this.outputRoot.exists() && this.outputRoot.isDirectory())) { throw new RuntimeException("Failed to create subdirs for " + type); } this.outputIpRoot = new File(tmp, type); this.outputIpRoot.mkdirs(); if (!(this.outputIpRoot.exists() && this.outputIpRoot.isDirectory())) { throw new RuntimeException("Failed to create subdirs for " + remoteAddr.getHostAddress() + "/" + type); } this.lastConfirmedFile = new File(this.outputIpRoot, LAST_CONFIRMED_FILENAME); if (!lastConfirmedFile.exists()) { try { this.lastConfirmedFile.createNewFile(); } catch (final IOException e) { LOGGER.fatal("Failed to create file: " + LAST_CONFIRMED_FILENAME); throw new RuntimeException(e); } } try { prepareForSubscribe(); } catch (final Exception e) { LOGGER.fatal("Failed to clean existing directories: "); LOGGER.fatal(e); throw new RuntimeException(e); } }
From source file:ac.dynam.rundeck.plugin.resources.ovirt.InstanceToNodeMapper.java
/** * Convert an oVirt Instance to a RunDeck INodeEntry based on the mapping input *//* ww w . j a v a2 s. c o m*/ @SuppressWarnings("unchecked") static INodeEntry instanceToNode(final VM inst) throws GeneratorException { final NodeEntryImpl node = new NodeEntryImpl(); node.setNodename(inst.getName()); node.setOsArch(inst.getCpu().getArchitecture()); node.setOsName(inst.getOs().getType()); node.setDescription(inst.getDescription()); node.setUsername("root"); InetAddress address = null; if (inst.getGuestInfo() != null) { try { address = InetAddress.getByName(inst.getGuestInfo().getFqdn()); logger.debug("Host " + node.getNodename() + " Guest FQDN " + inst.getGuestInfo().getFqdn() + " Address: " + address.getHostName()); if (address.getHostName() == "localhost") throw new UnknownHostException(); } catch (UnknownHostException e) { /* try the first IP instead then */ logger.warn("Host " + node.getNodename() + " address " + inst.getGuestInfo().getFqdn() + " does not resolve. Trying IP addresses instead"); for (int i = 0; i < inst.getGuestInfo().getIps().getIPs().size(); i++) { logger.debug("Host " + node.getNodename() + " Trying " + inst.getGuestInfo().getIps().getIPs().get(i).getAddress()); try { address = InetAddress.getByName(inst.getGuestInfo().getIps().getIPs().get(i).getAddress()); if (address != null) { if (address.isLinkLocalAddress() || address.isMulticastAddress()) { logger.warn("Host " + node.getNodename() + " ip address is not valid: " + inst.getGuestInfo().getIps().getIPs().get(i).getAddress()); continue; } logger.debug("Host " + node.getNodename() + " ip address " + address.getHostAddress() + " will be used instead"); break; } } catch (UnknownHostException e1) { logger.warn("Host " + node.getNodename() + " IP Address " + inst.getGuestInfo().getIps().getIPs().get(i).getAddress() + " is invalid"); } } } } if (address == null) { /* try resolving based on name */ try { address = InetAddress.getByName(node.getNodename()); } catch (UnknownHostException e) { logger.warn("Unable to Find IP address for Host " + node.getNodename()); return null; } } if (address != null) node.setHostname(address.getCanonicalHostName()); if (inst.getTags() != null) { VMTags tags = inst.getTags(); final HashSet<String> tagset = new HashSet<String>(); try { for (int j = 0; j < tags.list().size(); j++) { tagset.add(tags.list().get(j).getName()); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (null == node.getTags()) { node.setTags(tagset); } else { final HashSet<String> orig = new HashSet<String>(node.getTags()); orig.addAll(tagset); node.setTags(orig); } } if (inst.getHighAvailability().getEnabled()) node.setAttribute("HighAvailability", "true"); if (inst.getType() != null) node.setAttribute("Host Type", inst.getType()); node.setAttribute("oVirt VM", "true"); node.setAttribute("oVirt Host", inst.getHost().getName()); return node; }
From source file:com.oneops.inductor.Config.java
/** * Retruns the inductor IP address (IPV4 address). If there are multiple * NICs/IfAddresses, it selects the first one. Openstack VMs normally has * only one network interface (eth0)./* w ww. j a v a 2s . c o m*/ * * @return IPV4 address of inductor with interface name. Returns * <code>null</code> if it couldn't find anything. */ private String getInductorIPv4Addr() { try { Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); while (nics.hasMoreElements()) { NetworkInterface nic = nics.nextElement(); if (nic.isUp() && !nic.isLoopback()) { Enumeration<InetAddress> addrs = nic.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress add = addrs.nextElement(); // Print only IPV4 address if (add instanceof Inet4Address && !add.isLoopbackAddress()) { // Log the first one. String ip = add.getHostAddress() + " (" + nic.getDisplayName() + ")"; logger.info("Inductor IP : " + ip); return ip; } } } } } catch (Exception e) { logger.warn("Error getting inductor IP address", e); // Skip any errors } return null; }
From source file:com.twineworks.kettle.ruby.step.execmodels.SimpleExecutionModel.java
public RubyHash createRubyInputRow(RowMetaInterface rowMeta, Object[] r) throws KettleException { // create a hash for the row, they are not reused on purpose, so the scripting user can safely use them to store entire rows between invocations RubyHash rubyRow = new RubyHash(data.runtime); String[] fieldNames = rowMeta.getFieldNames(); for (int i = 0; i < fieldNames.length; i++) { String field = fieldNames[i]; // null values don't need no special treatment, they'll become nil if (r[i] == null) { rubyRow.put(field, null);//from w w w .j av a2s . c o m } else { ValueMetaInterface vm = rowMeta.getValueMeta(i); switch (vm.getType()) { case ValueMetaInterface.TYPE_BOOLEAN: rubyRow.put(field, vm.getBoolean(r[i])); break; case ValueMetaInterface.TYPE_INTEGER: rubyRow.put(field, vm.getInteger(r[i])); break; case ValueMetaInterface.TYPE_STRING: rubyRow.put(field, vm.getString(r[i])); break; case ValueMetaInterface.TYPE_NUMBER: rubyRow.put(field, vm.getNumber(r[i])); break; case ValueMetaInterface.TYPE_NONE: rubyRow.put(field, r[i]); break; case ValueMetaInterface.TYPE_SERIALIZABLE: if (r[i] instanceof RubyStepMarshalledObject) { Object restoredObject = getMarshal().callMethod(data.runtime.getCurrentContext(), "restore", data.runtime.newString(r[i].toString())); rubyRow.put(field, restoredObject); } else { // try to put the object in there as it is.. should create a nice adapter for the java object rubyRow.put(field, r[i]); } break; case ValueMetaInterface.TYPE_BINARY: // put a ruby array with bytes in there, that is expensive and should probably be avoided rubyRow.put(fieldNames[i], data.runtime.newArrayNoCopy(JavaUtil.convertJavaArrayToRuby(data.runtime, ArrayUtils.toObject((byte[]) vm.getBinary(r[i]))))); break; case ValueMetaInterface.TYPE_BIGNUMBER: IRubyObject bigDecimalObject = getBigDecimal().callMethod(data.runtime.getCurrentContext(), "new", data.runtime.newString((vm.getBigNumber(r[i])).toString())); rubyRow.put(field, bigDecimalObject); break; case ValueMetaInterface.TYPE_DATE: rubyRow.put(field, data.runtime.newTime((vm.getDate(r[i])).getTime())); break; case ValueMetaInterface.TYPE_TIMESTAMP: ValueMetaTimestamp vmTimestamp = (ValueMetaTimestamp) vm; Timestamp ts = vmTimestamp.getTimestamp(r[i]); RubyTime rubyTime = data.runtime.newTime(ts.getTime() / 1000 * 1000); rubyTime.setNSec(ts.getNanos()); rubyRow.put(field, rubyTime); break; case ValueMetaInterface.TYPE_INET: ValueMetaInternetAddress vmInet = (ValueMetaInternetAddress) vm; InetAddress ip = vmInet.getInternetAddress(r[i]); IRubyObject ipObject = getIPAddr().callMethod(data.runtime.getCurrentContext(), "new", data.runtime.newString(ip.getHostAddress())); rubyRow.put(field, ipObject); break; } } } return rubyRow; }
From source file:org.alfresco.filesys.AbstractServerConfigurationBean.java
/** * Parse an adapter name string and return the matching address * /*from w w w .j a va 2s . c om*/ * @param adapter String * @return InetAddress * @exception InvalidConfigurationException */ protected final InetAddress parseAdapterName(String adapter) throws InvalidConfigurationException { NetworkInterface ni = null; try { ni = NetworkInterface.getByName(adapter); } catch (SocketException ex) { throw new InvalidConfigurationException("Invalid adapter name, " + adapter); } if (ni == null) throw new InvalidConfigurationException("Invalid network adapter name, " + adapter); // Get the IP address for the adapter InetAddress adapAddr = null; Enumeration<InetAddress> addrEnum = ni.getInetAddresses(); while (addrEnum.hasMoreElements() && adapAddr == null) { // Get the current address InetAddress addr = addrEnum.nextElement(); if (IPAddress.isNumericAddress(addr.getHostAddress())) adapAddr = addr; } // Check if we found the IP address to bind to if (adapAddr == null) throw new InvalidConfigurationException("Adapter " + adapter + " does not have a valid IP address"); // Return the adapter address return adapAddr; }