List of usage examples for java.net NetworkInterface getByName
public static NetworkInterface getByName(String name) throws SocketException
From source file:org.jcommon.com.util.jmx.RmiAdptor.java
static private InetAddress getIPv4InetAddress() throws SocketException, UnknownHostException { String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) { NetworkInterface ni = NetworkInterface.getByName("eth0"); Enumeration<InetAddress> ias = ni.getInetAddresses(); InetAddress iaddress;/*from www . j av a 2 s .c om*/ do { iaddress = ias.nextElement(); } while (!(iaddress instanceof Inet4Address)); return iaddress; } return InetAddress.getLocalHost(); // for Windows and OS X it should work well }
From source file:com.cloud.utils.net.NetUtils.java
public static String getDefaultHostIp() { if (SystemUtils.IS_OS_WINDOWS) { final Pattern pattern = Pattern.compile("\\s*0.0.0.0\\s*0.0.0.0\\s*(\\S*)\\s*(\\S*)\\s*"); try {/*from w w w .j a v a2 s . com*/ final Process result = Runtime.getRuntime().exec("route print -4"); final BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream())); String line = output.readLine(); while (line != null) { final Matcher matcher = pattern.matcher(line); if (matcher.find()) { return matcher.group(2); } line = output.readLine(); } } catch (final IOException e) { s_logger.debug("Caught IOException", e); } return null; } else { NetworkInterface nic = null; final String pubNic = getDefaultEthDevice(); if (pubNic == null) { return null; } try { nic = NetworkInterface.getByName(pubNic); } catch (final SocketException e) { return null; } String[] info = null; try { info = NetUtils.getNetworkParams(nic); } catch (final NullPointerException ignored) { s_logger.debug("Caught NullPointerException when trying to getDefaultHostIp"); } if (info != null) { return info[0]; } return null; } }
From source file:ch.cyberduck.core.aquaticprime.Receipt.java
/** * Verifies the App Store Receipt/* w w w .ja va 2 s . co m*/ * * @return False if receipt validation failed. */ @Override public boolean verify() { try { Security.addProvider(new BouncyCastleProvider()); PKCS7SignedData signature = new PKCS7SignedData( IOUtils.toByteArray(new FileInputStream(this.getFile().getAbsolute()))); signature.verify(); // 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). // Extract the receipt attributes CMSSignedData s = new CMSSignedData(new FileInputStream(this.getFile().getAbsolute())); CMSProcessable signedContent = s.getSignedContent(); byte[] originalContent = (byte[]) signedContent.getContent(); ASN1Object asn = ASN1Object.fromByteArray(originalContent); byte[] opaque = null; String bundleIdentifier = null; String bundleVersion = null; byte[] hash = null; if (asn instanceof DERSet) { // 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. DERSet set = (DERSet) asn; Enumeration enumeration = set.getObjects(); while (enumeration.hasMoreElements()) { Object next = enumeration.nextElement(); if (next instanceof DERSequence) { DERSequence sequence = (DERSequence) next; DEREncodable type = sequence.getObjectAt(0); if (type instanceof DERInteger) { if (((DERInteger) type).getValue().intValue() == 2) { DEREncodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { bundleIdentifier = new String(((DEROctetString) value).getOctets(), "utf-8"); } } else if (((DERInteger) type).getValue().intValue() == 3) { DEREncodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { bundleVersion = new String(((DEROctetString) value).getOctets(), "utf-8"); } } else if (((DERInteger) type).getValue().intValue() == 4) { DEREncodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { opaque = ((DEROctetString) value).getOctets(); } } else if (((DERInteger) type).getValue().intValue() == 5) { DEREncodable 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("ch.sudo.cyberduck", StringUtils.trim(bundleIdentifier))) { log.error("Bundle identifier in ASN set does not match"); return false; } if (!StringUtils.equals(Preferences.instance().getDefault("CFBundleShortVersionString"), StringUtils.trim(bundleVersion))) { log.warn("Bundle version in ASN set does not match"); } NetworkInterface en0 = NetworkInterface.getByName("en0"); if (null == en0) { // Interface is not found when link is down #fail log.warn("No network interface en0"); } else { 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("Interface en0:" + hex); } // Compute the hash of the GUID MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(mac); digest.update(opaque); digest.update(bundleIdentifier.getBytes(Charset.forName("utf-8"))); byte[] result = digest.digest(); if (Arrays.equals(result, hash)) { if (log.isInfoEnabled()) { log.info(String.format("Valid receipt for GUID %s", hex)); } this.name = hex; } else { log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt", hex)); return false; } } } catch (Exception e) { log.error("Unknown receipt validation error", e); // Shutdown if receipt is not valid return false; } // Always return true to dismiss donation prompt. return true; }
From source file:org.apache.nifi.processor.util.listen.AbstractListenEventProcessor.java
@OnScheduled public void onScheduled(final ProcessContext context) throws IOException { charset = Charset.forName(context.getProperty(CHARSET).getValue()); port = context.getProperty(PORT).asInteger(); events = new LinkedBlockingQueue<>(context.getProperty(MAX_MESSAGE_QUEUE_SIZE).asInteger()); final String nicIPAddressStr = context.getProperty(NETWORK_INTF_NAME).evaluateAttributeExpressions() .getValue();/*from www . j a v a 2s. c o m*/ final int maxChannelBufferSize = context.getProperty(MAX_SOCKET_BUFFER_SIZE).asDataSize(DataUnit.B) .intValue(); InetAddress nicIPAddress = null; if (!StringUtils.isEmpty(nicIPAddressStr)) { NetworkInterface netIF = NetworkInterface.getByName(nicIPAddressStr); nicIPAddress = netIF.getInetAddresses().nextElement(); } // create the dispatcher and call open() to bind to the given port dispatcher = createDispatcher(context, events); dispatcher.open(nicIPAddress, port, maxChannelBufferSize); // start a thread to run the dispatcher final Thread readerThread = new Thread(dispatcher); readerThread.setName(getClass().getName() + " [" + getIdentifier() + "]"); readerThread.setDaemon(true); readerThread.start(); }
From source file:com.jagornet.dhcp.client.ClientSimulatorV6.java
/** * Parses the options.//from w ww .j a v a2 s .co m * * @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")) { numRequests = parseIntegerOption("num requests", cmd.getOptionValue("n"), 100); } mcastNetIf = DEFAULT_NETIF; if (cmd.hasOption("mi")) { try { mcastNetIf = NetworkInterface.getByName(cmd.getOptionValue("mi")); } catch (SocketException e) { e.printStackTrace(); return false; } } serverAddr = DEFAULT_ADDR; if (cmd.hasOption("sa")) { serverAddr = parseIpAddressOption("server", cmd.getOptionValue("sa"), DEFAULT_ADDR); } if (cmd.hasOption("cp")) { clientPort = parseIntegerOption("client port", cmd.getOptionValue("cp"), DhcpConstants.V6_CLIENT_PORT); } if (cmd.hasOption("sp")) { serverPort = parseIntegerOption("server port", cmd.getOptionValue("sp"), DhcpConstants.V6_SERVER_PORT); } if (cmd.hasOption("r")) { rapidCommit = true; } if (cmd.hasOption("to")) { timeout = parseIntegerOption("timeout", cmd.getOptionValue("to"), 0); } if (cmd.hasOption("ps")) { poolSize = parseIntegerOption("pool size", cmd.getOptionValue("ps"), 0); } } catch (ParseException pe) { System.err.println("Command line option parsing failure: " + pe); return false; } return true; }
From source file:ws.argo.DemoWebClient.Browser.BrowserController.java
private static String getHostIPAddressFromString(String propIPAddress, String niName) { String hostIPAddr = propIPAddress; if (propIPAddress.equals("")) { // If the listenerIPAddress is blank, then try to get the ip address of // the interface try {// w w w.j ava 2 s .co m NetworkInterface ni = null; if (niName != null) ni = NetworkInterface.getByName(niName); if (ni == null) { LOGGER.info("Network Interface name not specified or incorrect. Defaulting to localhost"); hostIPAddr = InetAddress.getLocalHost().getHostAddress(); } else { if (!ni.isLoopback()) { Enumeration<InetAddress> ee = ni.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); if (i instanceof Inet4Address) { hostIPAddr = i.getHostAddress(); break; // get the first one an get out of the loop } } } } } catch (SocketException e) { LOGGER.warn("A socket exception occurred."); } catch (UnknownHostException e) { LOGGER.warn("Error finding Network Interface", e); } } return hostIPAddr; }
From source file:org.apache.nifi.processors.standard.ListenTCPRecord.java
@OnScheduled public void onScheduled(final ProcessContext context) throws IOException { this.port = context.getProperty(PORT).evaluateAttributeExpressions().asInteger(); final int readTimeout = context.getProperty(READ_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue(); final int maxSocketBufferSize = context.getProperty(MAX_SOCKET_BUFFER_SIZE).asDataSize(DataUnit.B) .intValue();/*from w ww . ja va2s .com*/ final int maxConnections = context.getProperty(MAX_CONNECTIONS).asInteger(); final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER) .asControllerService(RecordReaderFactory.class); // if the Network Interface Property wasn't provided then a null InetAddress will indicate to bind to all interfaces final InetAddress nicAddress; final String nicAddressStr = context.getProperty(NETWORK_INTF_NAME).evaluateAttributeExpressions() .getValue(); if (!StringUtils.isEmpty(nicAddressStr)) { NetworkInterface netIF = NetworkInterface.getByName(nicAddressStr); nicAddress = netIF.getInetAddresses().nextElement(); } else { nicAddress = null; } SSLContext sslContext = null; SslContextFactory.ClientAuth clientAuth = null; final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE) .asControllerService(SSLContextService.class); if (sslContextService != null) { final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue(); sslContext = sslContextService.createSSLContext(SSLContextService.ClientAuth.valueOf(clientAuthValue)); clientAuth = SslContextFactory.ClientAuth.valueOf(clientAuthValue); } // create a ServerSocketChannel in non-blocking mode and bind to the given address and port final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.bind(new InetSocketAddress(nicAddress, port)); this.dispatcher = new SocketChannelRecordReaderDispatcher(serverSocketChannel, sslContext, clientAuth, readTimeout, maxSocketBufferSize, maxConnections, recordReaderFactory, socketReaders, getLogger()); // start a thread to run the dispatcher final Thread readerThread = new Thread(dispatcher); readerThread.setName(getClass().getName() + " [" + getIdentifier() + "]"); readerThread.setDaemon(true); readerThread.start(); }
From source file:com.jagornet.dhcpv6.server.DhcpV6Server.java
/** * Gets the IPv6 network interfaces for the supplied interface names. * // w ww .ja v a 2 s. c o m * @param ifnames the interface names to locate NetworkInterfaces by * * @return the list of NetworkInterfaces that are up, support multicast, * and have at least one IPv6 address configured * * @throws SocketException the socket exception */ private List<NetworkInterface> getIPv6NetIfs(String[] ifnames) throws SocketException { List<NetworkInterface> netIfs = new ArrayList<NetworkInterface>(); for (String ifname : ifnames) { if (ifname.equals("*")) { return getAllIPv6NetIfs(); } NetworkInterface netIf = NetworkInterface.getByName(ifname); if (netIf == null) { // if not found by name, see if the name is actually an address try { InetAddress ipaddr = InetAddress.getByName(ifname); netIf = NetworkInterface.getByInetAddress(ipaddr); } catch (UnknownHostException ex) { log.warn("Unknown interface: " + ifname + ": " + ex); } } if (netIf != null) { if (netIf.isUp()) { // for multicast, the loopback interface is excluded if (netIf.supportsMulticast() && !netIf.isLoopback()) { boolean isV6 = false; List<InterfaceAddress> ifAddrs = netIf.getInterfaceAddresses(); for (InterfaceAddress ifAddr : ifAddrs) { if (ifAddr.getAddress() instanceof Inet6Address) { netIfs.add(netIf); isV6 = true; break; } } if (!isV6) { System.err.println("Interface is not configured for IPv6: " + netIf.getDisplayName()); return null; } } else { System.err.println("Interface does not support multicast: " + netIf.getDisplayName()); return null; } } else { System.err.println("Interface is not up: " + netIf.getDisplayName()); return null; } } else { System.err.println("Interface not found or inactive: " + ifname); return null; } } return netIfs; }
From source file:com.vmware.aurora.global.Configuration.java
/** * Gets the fqdn of cms server. If it's not presented, the method tries to * retrieve the ip address of first network interface and reports it as the * fqdn.// w w w. j ava 2s. c o m * * @return The FQDN of CMS. */ public static String getCmsFQDN() { String fqdn = Configuration.getString("cms.mgmtnet.fqdn"); if (fqdn == null || fqdn.isEmpty()) { try { // try to retrieve the ip addr of eth0 NetworkInterface net = NetworkInterface.getByName("eth0"); Enumeration<InetAddress> addresses = net.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); if (addr instanceof Inet4Address) { String ip = addr.toString(); fqdn = ip.substring(ip.lastIndexOf("/") + 1); break; } } } catch (Exception e) { logger.info("Error in retrieving ip of eth0", e); throw CommonException.INTERNAL(e); } } return fqdn; }
From source file:org.apache.hadoop.net.DNS.java
/** * Returns all the IPs associated with the provided interface, if any, as * a list of InetAddress objects./*from w w w . ja v a2 s. c o m*/ * * @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 list 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 * */ public static List<InetAddress> getIPsAsInetAddressList(String strInterface, boolean returnSubinterfaces) throws UnknownHostException { if ("default".equals(strInterface)) { return Arrays.asList(InetAddress.getByName(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 Arrays.asList(InetAddress.getByName(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)); } return new Vector<InetAddress>(allAddrs); }