List of usage examples for java.net NetworkInterface getByName
public static NetworkInterface getByName(String name) throws SocketException
From source file:com.jagornet.dhcp.server.JagornetDhcpServer.java
/** * Gets the IPv6 network interfaces for the supplied interface names. * //w w w. j av a2 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); return null; } } else { System.err.println("Interface does not support multicast: " + netIf); return null; } } else { System.err.println("Interface is not up: " + netIf); return null; } } else { System.err.println("Interface not found or inactive: " + ifname); return null; } } return netIfs; }
From source file:org.apache.nifi.web.server.JettyServer.java
private void configureConnectors(final Server server) throws ServerConfigurationException { // create the http configuration final HttpConfiguration httpConfiguration = new HttpConfiguration(); httpConfiguration.setRequestHeaderSize(HEADER_BUFFER_SIZE); httpConfiguration.setResponseHeaderSize(HEADER_BUFFER_SIZE); if (props.getPort() != null) { final Integer port = props.getPort(); if (port < 0 || (int) Math.pow(2, 16) <= port) { throw new ServerConfigurationException("Invalid HTTP port: " + port); }/*from w w w . ja v a2 s.c o m*/ logger.info("Configuring Jetty for HTTP on port: " + port); final List<Connector> serverConnectors = Lists.newArrayList(); final Map<String, String> httpNetworkInterfaces = props.getHttpNetworkInterfaces(); if (httpNetworkInterfaces.isEmpty() || httpNetworkInterfaces.values().stream() .filter(value -> !Strings.isNullOrEmpty(value)).collect(Collectors.toList()).isEmpty()) { // create the connector final ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration)); // set host and port if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.WEB_HTTP_HOST))) { http.setHost(props.getProperty(NiFiProperties.WEB_HTTP_HOST)); } http.setPort(port); serverConnectors.add(http); } else { // add connectors for all IPs from http network interfaces serverConnectors .addAll(Lists.newArrayList(httpNetworkInterfaces.values().stream().map(ifaceName -> { NetworkInterface iface = null; try { iface = NetworkInterface.getByName(ifaceName); } catch (SocketException e) { logger.error("Unable to get network interface by name {}", ifaceName, e); } if (iface == null) { logger.warn("Unable to find network interface named {}", ifaceName); } return iface; }).filter(Objects::nonNull) .flatMap(iface -> Collections.list(iface.getInetAddresses()).stream()) .map(inetAddress -> { // create the connector final ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration)); // set host and port http.setHost(inetAddress.getHostAddress()); http.setPort(port); return http; }).collect(Collectors.toList()))); } // add all connectors serverConnectors.forEach(server::addConnector); } if (props.getSslPort() != null) { final Integer port = props.getSslPort(); if (port < 0 || (int) Math.pow(2, 16) <= port) { throw new ServerConfigurationException("Invalid HTTPs port: " + port); } logger.info("Configuring Jetty for HTTPs on port: " + port); final List<Connector> serverConnectors = Lists.newArrayList(); final Map<String, String> httpsNetworkInterfaces = props.getHttpsNetworkInterfaces(); if (httpsNetworkInterfaces.isEmpty() || httpsNetworkInterfaces.values().stream() .filter(value -> !Strings.isNullOrEmpty(value)).collect(Collectors.toList()).isEmpty()) { final ServerConnector https = createUnconfiguredSslServerConnector(server, httpConfiguration); // set host and port if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.WEB_HTTPS_HOST))) { https.setHost(props.getProperty(NiFiProperties.WEB_HTTPS_HOST)); } https.setPort(port); serverConnectors.add(https); } else { // add connectors for all IPs from https network interfaces serverConnectors .addAll(Lists.newArrayList(httpsNetworkInterfaces.values().stream().map(ifaceName -> { NetworkInterface iface = null; try { iface = NetworkInterface.getByName(ifaceName); } catch (SocketException e) { logger.error("Unable to get network interface by name {}", ifaceName, e); } if (iface == null) { logger.warn("Unable to find network interface named {}", ifaceName); } return iface; }).filter(Objects::nonNull) .flatMap(iface -> Collections.list(iface.getInetAddresses()).stream()) .map(inetAddress -> { final ServerConnector https = createUnconfiguredSslServerConnector(server, httpConfiguration); // set host and port https.setHost(inetAddress.getHostAddress()); https.setPort(port); return https; }).collect(Collectors.toList()))); } // add all connectors serverConnectors.forEach(server::addConnector); } }
From source file:com.jagornet.dhcp.server.JagornetDhcpServer.java
private NetworkInterface getIPv4NetIf(String ifname) throws SocketException { NetworkInterface netIf = NetworkInterface.getByName(ifname); if (netIf == null) { // if not found by name, see if the name is actually an address try {// ww w. j ava 2 s. c om InetAddress ipaddr = InetAddress.getByName(ifname); netIf = NetworkInterface.getByInetAddress(ipaddr); } catch (UnknownHostException ex) { log.warn("Unknown interface: " + ifname + ": " + ex); } } if (netIf != null) { if (netIf.isUp()) { // the loopback interface is excluded if (!netIf.isLoopback()) { boolean isV4 = false; List<InterfaceAddress> ifAddrs = netIf.getInterfaceAddresses(); for (InterfaceAddress ifAddr : ifAddrs) { if (ifAddr.getAddress() instanceof Inet4Address) { isV4 = true; break; } } if (!isV4) { System.err.println("Interface is not configured for IPv4: " + netIf); return null; } } else { System.err.println("Interface is loopback: " + netIf); return null; } } else { System.err.println("Interface is not up: " + netIf); return null; } } else { System.err.println("Interface not found or inactive: " + ifname); return null; } return netIf; }
From source file:com.vuze.plugin.azVPN_Air.Checker.java
private int handleUnboundOrLoopback(InetAddress bindIP, StringBuilder sReply) { int newStatusID = STATUS_ID_OK; InetAddress newBindIP = null; NetworkInterface newBindNetworkInterface = null; String s;//from ww w . ja v a2s . c o m if (bindIP.isAnyLocalAddress()) { addReply(sReply, CHAR_WARN, "airvpn.vuze.unbound"); } else { addReply(sReply, CHAR_BAD, "airvpn.vuze.loopback"); } try { NetworkAdmin networkAdmin = NetworkAdmin.getSingleton(); // Find a bindable address that starts with 10. InetAddress[] bindableAddresses = networkAdmin.getBindableAddresses(); for (InetAddress bindableAddress : bindableAddresses) { if (matchesVPNIP(bindableAddress)) { newBindIP = bindableAddress; newBindNetworkInterface = NetworkInterface.getByInetAddress(newBindIP); addReply(sReply, CHAR_GOOD, "airvpn.found.bindable.vpn", new String[] { "" + newBindIP }); break; } } // Find a Network Interface that has an address that starts with 10. NetworkAdminNetworkInterface[] interfaces = networkAdmin.getInterfaces(); boolean foundNIF = false; for (NetworkAdminNetworkInterface networkAdminInterface : interfaces) { NetworkAdminNetworkInterfaceAddress[] addresses = networkAdminInterface.getAddresses(); for (NetworkAdminNetworkInterfaceAddress a : addresses) { InetAddress address = a.getAddress(); if (address instanceof Inet4Address) { if (matchesVPNIP(address)) { s = texts.getLocalisedMessageText("airvpn.possible.vpn", new String[] { "" + address, networkAdminInterface.getName() + " (" + networkAdminInterface.getDisplayName() + ")" }); if (newBindIP == null) { foundNIF = true; newBindIP = address; // Either one should work //newBindNetworkInterface = NetworkInterface.getByInetAddress(newBindIP); newBindNetworkInterface = NetworkInterface .getByName(networkAdminInterface.getName()); s = CHAR_GOOD + " " + s + ". " + texts.getLocalisedMessageText("airvpn.assuming.vpn"); } else if (address.equals(newBindIP)) { s = CHAR_GOOD + " " + s + ". " + texts.getLocalisedMessageText("airvpn.same.address"); foundNIF = true; } else { if (newStatusID != STATUS_ID_BAD) { newStatusID = STATUS_ID_WARN; } s = CHAR_WARN + " " + s + ". " + texts.getLocalisedMessageText("airvpn.not.same.address"); } addLiteralReply(sReply, s); if (rebindNetworkInterface) { // stops message below from being added, we'll rebind later foundNIF = true; } } } } } if (!foundNIF) { addReply(sReply, CHAR_BAD, "airvpn.interface.not.found"); } // Check if default routing goes through 10.*, by connecting to address // via socket. Address doesn't need to be reachable, just routable. // This works on Windows, but on Mac returns a wildcard address DatagramSocket socket = new DatagramSocket(); socket.connect(testSocketAddress, 0); InetAddress localAddress = socket.getLocalAddress(); socket.close(); if (!localAddress.isAnyLocalAddress()) { NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localAddress); s = texts.getLocalisedMessageText("airvpn.nonvuze.probable.route", new String[] { "" + localAddress, networkInterface == null ? "null" : networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" }); if ((localAddress instanceof Inet4Address) && matchesVPNIP(localAddress)) { if (newBindIP == null) { newBindIP = localAddress; newBindNetworkInterface = networkInterface; s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("airvpn.assuming.vpn"); } else if (localAddress.equals(newBindIP)) { s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("airvpn.same.address"); } else { // Vuze not bound. We already found a boundable address, but it's not this one /* Possibly good case: * - Vuze: unbound * - Found Bindable: 10.100.1.6 * - Default Routing: 10.255.1.1 * -> Split network */ if (newStatusID != STATUS_ID_BAD) { newStatusID = STATUS_ID_WARN; } s = CHAR_WARN + " " + s + " " + texts.getLocalisedMessageText("airvpn.not.same.future.address") + " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting") + " " + texts.getLocalisedMessageText( "default.routing.not.vpn.network.splitting.unbound"); } addLiteralReply(sReply, s); } else { s = CHAR_WARN + " " + s; if (!bindIP.isLoopbackAddress()) { s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting"); } if (newBindIP == null && foundNIF) { if (newStatusID != STATUS_ID_BAD) { newStatusID = STATUS_ID_WARN; } s += " " + texts .getLocalisedMessageText("default.routing.not.vpn.network.splitting.unbound"); } addLiteralReply(sReply, s); } } } catch (Exception e) { e.printStackTrace(); addReply(sReply, CHAR_BAD, "airvpn.nat.error", new String[] { e.toString() }); } if (newBindIP == null) { addReply(sReply, CHAR_BAD, "airvpn.vpn.ip.detect.fail"); return STATUS_ID_BAD; } rebindNetworkInterface(newBindNetworkInterface, newBindIP, sReply); return newStatusID; }
From source file:com.cloud.migration.Db20to21MigrationUtil.java
protected String getHost() { NetworkInterface nic = null;//from w ww .ja va2s. c o m String pubNic = getEthDevice(); if (pubNic == null) { return null; } try { nic = NetworkInterface.getByName(pubNic); } catch (final SocketException e) { return null; } String[] info = NetUtils.getNetworkParams(nic); return info[0]; }
From source file:org.apache.nifi.remote.StandardRemoteProcessGroup.java
@Override public void setNetworkInterface(final String interfaceName) { writeLock.lock();// w w w .jav a 2s . c o m try { this.networkInterfaceName = interfaceName; if (interfaceName == null) { this.localAddress = null; this.nicValidationResult = null; } else { try { final Enumeration<InetAddress> inetAddresses = NetworkInterface.getByName(interfaceName) .getInetAddresses(); if (inetAddresses.hasMoreElements()) { this.localAddress = inetAddresses.nextElement(); this.nicValidationResult = null; } else { this.localAddress = null; this.nicValidationResult = new ValidationResult.Builder().input(interfaceName) .subject("Network Interface Name").valid(false) .explanation( "No IP Address could be found that is bound to the interface with name " + interfaceName) .build(); } } catch (final Exception e) { this.localAddress = null; this.nicValidationResult = new ValidationResult.Builder().input(interfaceName) .subject("Network Interface Name").valid(false) .explanation("Could not obtain Network Interface with name " + interfaceName).build(); } } } finally { writeLock.unlock(); } }
From source file:org.pentaho.di.core.Const.java
/** * Get the primary IP address tied to a network interface (excluding loop-back etc) * * @param networkInterfaceName/*from ww w . j a v a 2 s.co m*/ * the name of the network interface to interrogate * @return null if the network interface or address wasn't found. * * @throws SocketException * in case of a security or network error */ public static final String getIPAddress(String networkInterfaceName) throws SocketException { NetworkInterface networkInterface = NetworkInterface.getByName(networkInterfaceName); Enumeration<InetAddress> ipAddresses = networkInterface.getInetAddresses(); while (ipAddresses.hasMoreElements()) { InetAddress inetAddress = ipAddresses.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress.toString().indexOf(":") < 0) { String hostname = inetAddress.getHostAddress(); return hostname; } } return null; }