List of usage examples for java.net NetworkInterface getDisplayName
public String getDisplayName()
From source file:com.chiralBehaviors.autoconfigure.AutoConfigure.java
/** * @return the host address to bind this service to *//*from w w w . ja va2 s . c o m*/ protected InetAddress determineHostAddress() { NetworkInterface iface = determineNetworkInterface(); InetAddress raw = null; for (Enumeration<InetAddress> interfaceAddresses = iface.getInetAddresses(); interfaceAddresses .hasMoreElements();) { if (!interfaceAddresses.hasMoreElements()) { String msg = String.format("Unable to find any network address for interface[%s] {%s}", iface.getName(), iface.getDisplayName()); logger.error(msg); throw new IllegalStateException(msg); } raw = interfaceAddresses.nextElement(); if (config.ipV6) { if (raw.getAddress().length == 6) { break; } } else if (raw.getAddress().length == 4) { break; } } if (raw == null) { String msg = String.format("Unable to find any network address for interface[%s] {%s}", iface.getName(), iface.getDisplayName()); logger.error(msg); throw new IllegalStateException(msg); } InetAddress address; try { address = InetAddress.getByName(raw.getCanonicalHostName()); } catch (UnknownHostException e) { String msg = String.format("Unable to resolve network address [%s] for interface[%s] {%s}", raw, iface.getName(), iface.getDisplayName()); logger.error(msg, e); throw new IllegalStateException(msg, e); } return address; }
From source file:ws.argo.DemoWebClient.Browser.BrowserController.java
/** * Return the ip info of where the web host lives that supports the browser * app.//www . ja v a 2 s. c om * * @return the ip addr info * @throws UnknownHostException if something goes wrong */ @GET @Path("/ipAddrInfo") public String getIPAddrInfo() throws UnknownHostException { Properties clientProps = getPropeSenderProps(); StringBuffer buf = new StringBuffer(); InetAddress localhost = null; NetworkInterface ni = null; try { localhost = InetAddress.getLocalHost(); LOGGER.debug("Network Interface name not specified. Using the NI for localhost " + localhost.getHostAddress()); ni = NetworkInterface.getByInetAddress(localhost); } catch (UnknownHostException | SocketException e) { LOGGER.error("Error occured dealing with network interface name lookup ", e); } buf.append("<p>").append("<span style='color: red'> IP Address: </span>") .append(localhost.getHostAddress()); buf.append("<span style='color: red'> Host name: </span>").append(localhost.getCanonicalHostName()); if (ni == null) { buf.append("<span style='color: red'> Network Interface is NULL </span>"); } else { buf.append("<span style='color: red'> Network Interface name: </span>").append(ni.getDisplayName()); } buf.append("</p><p>"); buf.append("Sending probes to " + respondToAddresses.size() + " addresses - "); for (ProbeRespondToAddress rta : respondToAddresses) { buf.append("<span style='color: red'> Probe to: </span>") .append(rta.respondToAddress + ":" + rta.respondToPort); } buf.append("</p>"); return buf.toString(); }
From source file:com.safi.asterisk.handler.SafletEngine.java
public List<String> getLocalIPAddresses() { List<String> iplist = new ArrayList<String>(); NetworkInterface iface = null; try {//from w w w . jav a 2 s . c o m for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces .hasMoreElements();) { iface = ifaces.nextElement(); System.out.println("Interface:" + iface.getDisplayName()); InetAddress ia = null; for (Enumeration<InetAddress> ips = iface.getInetAddresses(); ips.hasMoreElements();) { ia = ips.nextElement(); if (Pattern.matches(AbstractConnectionManager.PATTERN_IP, ia.getHostAddress())) { iplist.add(ia.getHostAddress()); } } } } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } return iplist; }
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;/* w w w .j a v a 2 s .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:org.chromium.ChromeSocket.java
private void getNetworkList(CordovaArgs args, final CallbackContext callbackContext) throws JSONException { try {/*w ww .j ava 2 s. co m*/ JSONArray list = new JSONArray(); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); NetworkInterface iface; // Enumerations are a crappy legacy API, can't use the for (foo : bar) syntax. while (interfaces.hasMoreElements()) { iface = interfaces.nextElement(); if (iface.isLoopback()) { continue; } for (InterfaceAddress interfaceAddress : iface.getInterfaceAddresses()) { InetAddress address = interfaceAddress.getAddress(); if (address != null) { JSONObject data = new JSONObject(); data.put("name", iface.getDisplayName()); // Strip percent suffix off of ipv6 addresses to match desktop behaviour. data.put("address", address.getHostAddress().replaceAll("%.*", "")); data.put("prefixLength", interfaceAddress.getNetworkPrefixLength()); list.put(data); } } } callbackContext.success(list); } catch (SocketException se) { callbackContext.error("SocketException: " + se); } }
From source file:org.rifidi.utilities.device.DeviceAddressManager.java
/** * This method enumerates all existing devices in the system. *//*from w w w .ja va 2s. c om*/ @SuppressWarnings("unchecked") private void enumerateSystemDevices() { /* This is the set which will eventually become the new device set */ Set<SystemDevice> enumeratedDevices = new TreeSet<SystemDevice>(); /* Grab the previous devices and put them in an easy to use list form */ List<SystemDevice> previouslyEnumeratedDevices = new ArrayList<SystemDevice>(this.systemDevices); /* Enumerate serial devices */ if (this.serialEnabled) { Enumeration commPorts = CommPortIdentifier.getPortIdentifiers(); while (commPorts.hasMoreElements()) { CommPortIdentifier curCommPort = (CommPortIdentifier) commPorts.nextElement(); if (curCommPort.getPortType() == CommPortIdentifier.PORT_SERIAL) { /* Make a serial port so that we can get baud settings, etc. */ RXTXPort tempPort = null; try { /* * Grab the serial port and get all of its current * settings */ tempPort = new RXTXPort(curCommPort.getName()); SystemSerialPort portToAdd = new SystemSerialPort(tempPort.getName(), tempPort.getName(), SystemDevice.DeviceExistenceType.PREVIOUSLY_EXISTING, tempPort.getBaudRate(), tempPort.getDataBits(), tempPort.getParity(), tempPort.getStopBits()); /* Check and see if the device already exists */ int existingDeviceIndex = previouslyEnumeratedDevices.indexOf(portToAdd); if (existingDeviceIndex != -1) { /* Grab that already existing device */ SystemSerialPort existingSerialDevice = (SystemSerialPort) previouslyEnumeratedDevices .get(existingDeviceIndex); /* Copy the creation state over */ portToAdd = new SystemSerialPort(tempPort.getName(), tempPort.getName(), existingSerialDevice.getDeviceExistenceType(), tempPort.getBaudRate(), tempPort.getDataBits(), tempPort.getParity(), tempPort.getStopBits()); } tempPort.close(); /* Add to enumerated devices */ enumeratedDevices.add(portToAdd); } catch (PortInUseException e) { logger.info(e.getMessage() + " (" + curCommPort.getName() + ")"); } } } } /* Enumerate IP devices and all addresses. */ /* Get all of the interfaces in the system and print them. */ Enumeration<NetworkInterface> netInterfaces = null; try { netInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { logger.warn(e.getMessage()); } /* Check to see if we have interfaces to add to the device list. */ if (netInterfaces != null) { /* Grab all of the interfaces and their network addresses */ while (netInterfaces.hasMoreElements()) { /* Grab the current interface */ NetworkInterface curInterface = netInterfaces.nextElement(); /* Use a tree map for sorted IPs */ Map<String, SystemNetworkInterface.NetworkAddressType> curInterfaceAddressMap; curInterfaceAddressMap = new TreeMap<String, SystemNetworkInterface.NetworkAddressType>(); /* Get all of the addresses which this interface has */ Enumeration<InetAddress> curInterfaceAddresses = curInterface.getInetAddresses(); while (curInterfaceAddresses.hasMoreElements()) { /* Append the current address to map */ InetAddress curAddress = curInterfaceAddresses.nextElement(); curInterfaceAddressMap.put(curAddress.getHostAddress(), SystemNetworkInterface.NetworkAddressType.PREVIOUSLY_EXISTING); } /* Create the new device */ SystemNetworkInterface interfaceToAdd = new SystemNetworkInterface(curInterface.getDisplayName(), curInterface.getName(), SystemDevice.DeviceExistenceType.PREVIOUSLY_EXISTING, curInterfaceAddressMap); /* Check and see if the device already exists */ int existingDeviceIndex = previouslyEnumeratedDevices.indexOf(interfaceToAdd); if (existingDeviceIndex != -1) { /* Grab that already existing device */ SystemNetworkInterface existingNetworkInterface = (SystemNetworkInterface) previouslyEnumeratedDevices .get(existingDeviceIndex); /* Copy over the existing device existence type */ interfaceToAdd = null; interfaceToAdd = new SystemNetworkInterface(curInterface.getDisplayName(), curInterface.getName(), existingNetworkInterface.getDeviceExistenceType(), curInterfaceAddressMap); /* Copy over the address info */ Iterator<String> addressIter = interfaceToAdd.getNetworkAddresses().keySet().iterator(); /* Check each IP and see if it is previously existing */ while (addressIter.hasNext()) { String curAddress = addressIter.next(); SystemNetworkInterface.NetworkAddressType existingType = existingNetworkInterface .getNetworkAddresses().get(curAddress); /* Preserve the existing type */ if (existingType != null) { interfaceToAdd.getNetworkAddresses().put(curAddress, existingType); } } } /* Add the new device to the existing devices list */ enumeratedDevices.add(interfaceToAdd); } } /* Blow out the old system devices */ this.systemDevices.clear(); /* Assign the new system devices */ this.systemDevices = enumeratedDevices; }
From source file:com.jagornet.dhcpv6.server.DhcpV6Server.java
/** * Gets the IPv6 network interfaces for the supplied interface names. * //from w w w . j av 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:org.onosproject.ospf.controller.impl.Controller.java
/** * Tell controller that we're ready to handle channels. *///from w w w . j av a 2 s .c o m public void run() { try { //get the configuration from json file List<OSPFArea> areas = getConfiguration(); //get the connected interfaces Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); // Check NetworkInterfaces and area-config have same IP Address for (NetworkInterface netInt : Collections.list(nets)) { // if the interface is up & not loopback if (!netInt.isUp() && !netInt.isLoopback()) { continue; } //get all the InetAddresses Enumeration<InetAddress> inetAddresses = netInt.getInetAddresses(); for (InetAddress inetAddress : Collections.list(inetAddresses)) { String ipAddress = inetAddress.getHostAddress(); //Search for the address in all configured areas interfaces for (OSPFArea area : areas) { for (OSPFInterface ospfIf : area.getInterfacesLst()) { String ipFromConfig = ospfIf.getIpAddress(); if (ipFromConfig.trim().equals(ipAddress.trim())) { log.debug("Both Config and Interface have ipAddress {} for area {}", ipAddress, area.getAreaID()); // if same IP address create try { log.debug("Creating ServerBootstrap for {} @ {}", ipAddress, ospfPort); final ServerBootstrap bootstrap = createServerBootStrap(); bootstrap.setOption("reuseAddr", true); bootstrap.setOption("child.keepAlive", true); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.sendBufferSize", Controller.BUFFER_SIZE); //Set the interface name in ospfInterface ospfIf.setInterfaceName(netInt.getDisplayName()); //netInt.get // passing OSPFArea and interface to pipelinefactory ChannelPipelineFactory pfact = new OSPFPipelineFactory(this, null, area, ospfIf); bootstrap.setPipelineFactory(pfact); InetSocketAddress sa = new InetSocketAddress(InetAddress.getByName(ipAddress), ospfPort); cg = new DefaultChannelGroup(); cg.add(bootstrap.bind(sa)); log.debug("Listening for connections on {}", sa); //For testing. remove this interfc = ospfIf; //Start aging process area.initializeDB(); area.initializeArea(); } catch (Exception e) { throw new RuntimeException(e); } } } } } } } catch (Exception e) { log.error("Error::Controller:: {}", e.getMessage()); } }
From source file:org.openhab.binding.harmonyhub.discovery.HarmonyHubDiscovery.java
/** * Send broadcast message over all active interfaces * * @param discoverString/*from www .j a v a 2s. co m*/ * String to be used for the discovery */ private void sendDiscoveryMessage(String discoverString) { DatagramSocket bcSend = null; try { bcSend = new DatagramSocket(); bcSend.setBroadcast(true); byte[] sendData = discoverString.getBytes(); // Broadcast the message over all the network interfaces Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress[] broadcast = null; if (StringUtils.isNotBlank(optionalHost)) { try { broadcast = new InetAddress[] { InetAddress.getByName(optionalHost) }; } catch (Exception e) { logger.error("Could not use host for hub discovery", e); return; } } else { broadcast = new InetAddress[] { InetAddress.getByName("224.0.0.1"), InetAddress.getByName("255.255.255.255"), interfaceAddress.getBroadcast() }; } for (InetAddress bc : broadcast) { // Send the broadcast package! if (bc != null) { try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc, DISCO_PORT); bcSend.send(sendPacket); } catch (IOException e) { logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage()); } catch (Exception e) { logger.debug(e.getMessage(), e); } logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(), networkInterface.getDisplayName()); } } } } } catch (IOException e) { logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage()); } finally { try { if (bcSend != null) { bcSend.close(); } } catch (Exception e) { // Ignore } } }
From source file:com.chiralBehaviors.autoconfigure.AutoConfigure.java
/** * @return the network interface to bind this interface to. */// w ww. ja va2 s . c o m protected NetworkInterface determineNetworkInterface() { NetworkInterface iface; if (config.networkInterface == null) { try { iface = NetworkInterface.getByIndex(1); } catch (SocketException e) { String msg = String.format("Unable to obtain default network interface"); logger.error(msg, e); throw new IllegalStateException(msg, e); } } else { try { iface = NetworkInterface.getByName(config.networkInterface); } catch (SocketException e) { String msg = String.format("Unable to obtain network interface[%s]", config.networkInterface); logger.error(msg, e); throw new IllegalStateException(msg, e); } if (iface == null) { String msg = String.format("Unable to find network interface [%s]", config.networkInterface); logger.error(msg); throw new IllegalStateException(msg); } } try { if (!iface.isUp()) { String msg = String.format("Network interface [%s] is not up!", iface.getName()); logger.error(msg); throw new IllegalStateException(msg); } } catch (SocketException e) { String msg = String.format("Unable to determine if network interface [%s] is up", iface.getName()); logger.error(msg); throw new IllegalStateException(msg); } logger.info(String.format("Network interface [%s] is up", iface.getDisplayName())); return iface; }