List of usage examples for java.net NetworkInterface getByName
public static NetworkInterface getByName(String name) throws SocketException
From source file:org.droidupnp.Main.java
private static InetAddress getLocalIpAdressFromIntf(String intfName) { try {/*from ww w . j ava2 s . co m*/ NetworkInterface intf = NetworkInterface.getByName(intfName); if (intf.isUp()) { for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) return inetAddress; } } } catch (Exception e) { Log.w(TAG, "Unable to get ip adress for interface " + intfName); } return null; }
From source file:com.ery.ertc.estorm.util.DNS.java
/** * Returns all the IPs associated with the provided interface, if any, in textual form. * /*from ww w . j av a 2s.c o m*/ * @param strInterface * The name of the network interface or subinterface 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 * @throws UnknownHostException * If an UnknownHostException is encountered in querying the default interface or the given interface can not be found * */ public static String[] getIPs(String strInterface, boolean returnSubinterfaces) throws UnknownHostException { if ("default".equals(strInterface)) { return new String[] { InetAddress.getLocalHost().getHostAddress() }; } NetworkInterface netIf; try { netIf = NetworkInterface.getByName(strInterface); if (netIf == null) { netIf = getSubinterface(strInterface); if (netIf == null) { throw new UnknownHostException("Unknown interface " + strInterface); } } } catch (SocketException e) { LOG.warn("Unable to get IP for interface " + strInterface, e); return new String[] { InetAddress.getLocalHost().getHostAddress() }; } // 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: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 *//*w w w . j av a 2 s .c om*/ 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:org.apache.nifi.processors.rt.DeviceRegistryReportingTask.java
private NiFiDevice populateNetworkingInfo(NiFiDevice device) { InetAddress ip;/*from w w w . j a va2s . co m*/ try { ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); //Check this isn't null if (network == null) { //Hail mary to try and get eth0 getLogger().warn( "Hardcoded getting network interface by ETH0 which could be the incorrect interface but others were null"); network = NetworkInterface.getByName("eth0"); } byte[] mac = network.getHardwareAddress(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < mac.length; i++) { sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : "")); } //Set the values to the device object. device.setDeviceId(sb.toString()); device.setIp(ip.getHostAddress()); String hostname = InetAddress.getLocalHost().getHostName(); logger.error("First attempt at getting hostname: " + hostname); if (!StringUtils.isEmpty(hostname)) { device.setHostname(hostname); } else { //Try the linux approach ... could fail if hostname(1) system command is not available. try { Process process = Runtime.getRuntime().exec("hostname"); InputStream is = process.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); hostname = writer.toString(); if (StringUtils.isEmpty(hostname)) { device.setHostname("UNKNOWN"); } else { device.setHostname(hostname); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error attempting to resolve hostname", ex); } } } catch (UnknownHostException e) { e.printStackTrace(); logger.error("Unknown host exception getting hostname", e); } catch (SocketException e) { e.printStackTrace(); logger.error("socket exception getting hostname", e); } return device; }
From source file:org.blue.star.plugins.check_ping.java
public void process_command_option(Option o) throws IllegalArgumentException { String optarg = o.getValue(); switch (o.getId()) { case '4': /* IPv4 only */ address_family = common_h.AF_INET; break;/*from w ww . j a v a 2s . com*/ case '6': /* IPv6 only */ address_family = common_h.AF_INET6; // TODO Determine if IPv6 is even available. break; case 'H': /* hostname */ String[] hostnames = optarg.split(","); for (String hostname : hostnames) addresses.add(hostname); n_addresses = addresses.size(); break; case 'p': /* number of packets to send */ if (utils.is_intnonneg(optarg)) max_packets = Integer.parseInt(optarg); else throw new IllegalArgumentException(utils.formatArgumentError(this.getClass().getName(), "<max_packets> (%s) must be a non-negative number\n", optarg)); break; case 'n': /* no HTML */ display_html = false; break; case 'L': /* show HTML */ display_html = true; break; case 'c': crta = get_threshold_rta(optarg); cpl = get_threshold_pl(optarg); break; case 'w': wrta = get_threshold_rta(optarg); wpl = get_threshold_pl(optarg); break; case 'i': interface_name = optarg; try { network_interface = NetworkInterface.getByName(interface_name); } catch (Exception e) { throw new IllegalArgumentException("Error acquiring acces to interface " + e.getMessage()); } if (network_interface == null) { throw new IllegalArgumentException("Interface name " + interface_name + " is not available."); } break; } }
From source file:ws.argo.BrowserWeb.BrowserWebController.java
private Properties getPropeGeneratorProps() throws UnknownHostException { if (pgProps != null) return pgProps; InputStream in = getPropertiesFileInputStream(); pgProps = new Properties(); if (in != null) { try {//from w w w . j a va 2 s . c om pgProps.load(in); } catch (IOException e) { // TODO Auto-generated catch block // Should log the props file issue setDefaultProbeGeneratorProperties(pgProps); } } if (pgProps.getProperty("listenerIPAddress", "").equals("")) { // If the listenerIPAddress is blank, then try to get the ip address of the interface String hostIPAddr = null; try { NetworkInterface n = NetworkInterface .getByName(pgProps.getProperty("listenerInterfaceName", "en0")); if (!n.isLoopback()) { Enumeration ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); hostIPAddr = i.getHostName(); System.out.println(hostIPAddr); } } } catch (SocketException e) { System.out.println("A socket exception occurred."); } if (hostIPAddr == null) { hostIPAddr = InetAddress.getLocalHost().getHostName(); System.out.println("Defaulting to local address: " + hostIPAddr); } pgProps.put("listenerIPAddress", hostIPAddr); } return pgProps; }
From source file:org.apereo.portal.PortalInfoProviderImpl.java
protected String getNetworkInterfaceName(String networkInterfaceName) { if (networkInterfaceName == null) { return null; }//from www .j a v a 2 s . c om this.logger.info("Attempting to resolve serverName using NetworkInterface named ({})", networkInterfaceName); final NetworkInterface networkInterface; try { networkInterface = NetworkInterface.getByName(networkInterfaceName); } catch (SocketException e) { logger.warn("Failed to get NetworkInterface for name (" + networkInterfaceName + ").", e); return null; } if (networkInterface == null) { logger.warn("No NetworkInterface could be found for name (" + networkInterfaceName + "). Available interface names: " + getNetworkInterfaceNames()); return null; } final Enumeration<InetAddress> inetAddressesEnum = networkInterface.getInetAddresses(); if (!inetAddressesEnum.hasMoreElements()) { logger.warn("NetworkInterface (" + networkInterface.getName() + ") has no InetAddresses to get a name from."); return null; } final InetAddress inetAddress = inetAddressesEnum.nextElement(); if (inetAddressesEnum.hasMoreElements()) { logger.warn("NetworkInterface (" + networkInterface.getName() + ") has more than one InetAddress, the hostName of the first will be returned."); } return inetAddress.getHostName(); }
From source file:org.apache.cassandra.config.DatabaseDescriptor.java
private static InetAddress getNetworkInterfaceAddress(String intf, String configName, boolean preferIPv6) throws ConfigurationException { try {//from w w w. j a v a 2s . c om NetworkInterface ni = NetworkInterface.getByName(intf); if (ni == null) throw new ConfigurationException( "Configured " + configName + " \"" + intf + "\" could not be found", false); Enumeration<InetAddress> addrs = ni.getInetAddresses(); if (!addrs.hasMoreElements()) throw new ConfigurationException( "Configured " + configName + " \"" + intf + "\" was found, but had no addresses", false); /* * Try to return the first address of the preferred type, otherwise return the first address */ InetAddress retval = null; while (addrs.hasMoreElements()) { InetAddress temp = addrs.nextElement(); if (preferIPv6 && temp instanceof Inet6Address) return temp; if (!preferIPv6 && temp instanceof Inet4Address) return temp; if (retval == null) retval = temp; } return retval; } catch (SocketException e) { throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" caused an exception", e); } }
From source file:com.jagornet.dhcpv6.client.TestClient.java
/** * Parses the options./*from w ww . j av a 2 s .c om*/ * * @param args the args * * @return true, if successful */ protected boolean parseOptions(String[] args) { try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("?")) { return false; } if (cmd.hasOption("n")) { String n = cmd.getOptionValue("n"); try { numRequests = Integer.parseInt(n); } catch (NumberFormatException ex) { numRequests = 100; System.err.println("Invalid number of requests: '" + n + "' using default: " + numRequests + " Exception=" + ex); } } if (cmd.hasOption("a")) { String a = cmd.getOptionValue("a"); try { serverAddr = InetAddress.getByName(a); } catch (UnknownHostException ex) { serverAddr = DhcpConstants.LOCALHOST_V6; System.err.println( "Invalid address: '" + a + "' using default: " + serverAddr + " Exception=" + ex); } } if (cmd.hasOption("m")) { String m = cmd.getOptionValue("m"); try { mcastNetIf = NetworkInterface.getByName(m); } catch (SocketException ex) { System.err.println("Invalid interface: " + m + " - " + ex); } } if (cmd.hasOption("cp")) { String p = cmd.getOptionValue("cp"); try { clientPort = Integer.parseInt(p); } catch (NumberFormatException ex) { clientPort = DhcpConstants.CLIENT_PORT; System.err.println("Invalid client port number: '" + p + "' using default: " + clientPort + " Exception=" + ex); } } if (cmd.hasOption("sp")) { String p = cmd.getOptionValue("sp"); try { serverPort = Integer.parseInt(p); } catch (NumberFormatException ex) { serverPort = DhcpConstants.SERVER_PORT; System.err.println("Invalid server port number: '" + p + "' using default: " + serverPort + " Exception=" + ex); } } if (cmd.hasOption("r")) { rapidCommit = true; } } catch (ParseException pe) { System.err.println("Command line option parsing failure: " + pe); return false; } return true; }
From source file:ch.cyberduck.core.aquaticprime.ReceiptVerifier.java
@Override public boolean verify(final LicenseVerifierCallback callback) { try {/*from ww w. j a v a 2 s . c om*/ // For additional security, you may verify the fingerprint of the root CA and the OIDs of the // intermediate CA and signing certificate. The OID in the Certificate Policies Extension of the // intermediate CA is (1 2 840 113635 100 5 6 1), and the Marker OID of the signing certificate // is (1 2 840 113635 100 6 11 1). final CMSSignedData s = new CMSSignedData(new FileInputStream(file.getAbsolute())); Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); for (SignerInformation signer : signers.getSigners()) { final Collection<X509CertificateHolder> matches = certs.getMatches(signer.getSID()); for (X509CertificateHolder holder : matches) { if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder() .setProvider(new BouncyCastleProvider()).build(holder))) { return false; } } } // Extract the receipt attributes final CMSProcessable signedContent = s.getSignedContent(); byte[] originalContent = (byte[]) signedContent.getContent(); final ASN1Primitive asn = ASN1Primitive.fromByteArray(originalContent); byte[] opaque = null; String bundleIdentifier = null; String bundleVersion = null; byte[] hash = null; if (asn instanceof ASN1Set) { // 2 Bundle identifier Interpret as an ASN.1 UTF8STRING. // 3 Application version Interpret as an ASN.1 UTF8STRING. // 4 Opaque value Interpret as a series of bytes. // 5 SHA-1 hash Interpret as a 20-byte SHA-1 digest value. final ASN1Set set = (ASN1Set) asn; final Enumeration enumeration = set.getObjects(); while (enumeration.hasMoreElements()) { Object next = enumeration.nextElement(); if (next instanceof DLSequence) { DLSequence sequence = (DLSequence) next; ASN1Encodable type = sequence.getObjectAt(0); if (type instanceof ASN1Integer) { if (((ASN1Integer) type).getValue().intValue() == 2) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { bundleIdentifier = new String(((DEROctetString) value).getOctets(), "UTF-8"); } } else if (((ASN1Integer) type).getValue().intValue() == 3) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { bundleVersion = new String(((DEROctetString) value).getOctets(), "UTF-8"); } } else if (((ASN1Integer) type).getValue().intValue() == 4) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { opaque = ((DEROctetString) value).getOctets(); } } else if (((ASN1Integer) type).getValue().intValue() == 5) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { hash = ((DEROctetString) value).getOctets(); } } } } } } else { log.error(String.format("Expected set of attributes for %s", asn)); return false; } if (!StringUtils.equals(application, StringUtils.trim(bundleIdentifier))) { log.error(String.format("Bundle identifier %s in ASN set does not match", bundleIdentifier)); return false; } if (!StringUtils.equals(version, StringUtils.trim(bundleVersion))) { log.warn(String.format("Bundle version %s in ASN set does not match", bundleVersion)); } final NetworkInterface en0 = NetworkInterface.getByName("en0"); if (null == en0) { // Interface is not found when link is down #fail log.warn("No network interface en0"); return true; } else { final byte[] mac = en0.getHardwareAddress(); if (null == mac) { log.error("Cannot determine MAC address"); // Continue without validation return true; } final String hex = Hex.encodeHexString(mac); if (log.isDebugEnabled()) { log.debug(String.format("Interface en0 %s", hex)); } // Compute the hash of the GUID final MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(mac); if (null == opaque) { log.error(String.format("Missing opaque string in ASN.1 set %s", asn)); return false; } digest.update(opaque); if (null == bundleIdentifier) { log.error(String.format("Missing bundle identifier in ASN.1 set %s", asn)); return false; } digest.update(bundleIdentifier.getBytes(Charset.forName("UTF-8"))); final byte[] result = digest.digest(); if (Arrays.equals(result, hash)) { if (log.isInfoEnabled()) { log.info(String.format("Valid receipt for GUID %s", hex)); } guid = hex; return true; } else { log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt", hex)); return false; } } } catch (IOException | GeneralSecurityException | CMSException | SecurityException e) { log.error("Receipt validation error", e); // Shutdown if receipt is not valid return false; } catch (Exception e) { log.error("Unknown receipt validation error", e); return true; } }