List of usage examples for java.net NetworkInterface getInterfaceAddresses
public java.util.List<InterfaceAddress> getInterfaceAddresses()
From source file:org.openremote.controller.service.BeehiveCommandCheckService.java
public static String getMACAddresses() throws Exception { StringBuilder macs = new StringBuilder(); Enumeration<NetworkInterface> enum1 = NetworkInterface.getNetworkInterfaces(); while (enum1.hasMoreElements()) { NetworkInterface networkInterface = enum1.nextElement(); if (!networkInterface.isLoopback()) { boolean onlyLinkLocal = true; for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { if (!interfaceAddress.getAddress().isLinkLocalAddress()) { onlyLinkLocal = false; }//from w w w .ja v a 2s. c o m } if (onlyLinkLocal) { continue; } byte[] mac = networkInterface.getHardwareAddress(); if (mac != null) { macs.append(getMACString(networkInterface.getHardwareAddress())); macs.append(","); } } } if (macs.length() == 0) { return "no-mac-address-found"; } macs.deleteCharAt(macs.length() - 1); return macs.toString(); }
From source file:org.openhab.binding.zway.internal.discovery.ZWayBridgeDiscoveryService.java
private void scan() { logger.debug("Starting scan for Z-Way Server"); ValidateIPV4 validator = new ValidateIPV4(); try {/*w ww .j a v a 2s .c o m*/ Enumeration<NetworkInterface> enumNetworkInterface = NetworkInterface.getNetworkInterfaces(); while (enumNetworkInterface.hasMoreElements()) { NetworkInterface networkInterface = enumNetworkInterface.nextElement(); if (networkInterface.isUp() && !networkInterface.isVirtual() && !networkInterface.isLoopback()) { for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { if (validator.isValidIPV4(address.getAddress().getHostAddress())) { String ipAddress = address.getAddress().getHostAddress(); Short prefix = address.getNetworkPrefixLength(); logger.debug("Scan IP address for Z-Way Server: {}", ipAddress); // Search on localhost first scheduler.execute(new ZWayServerScan(ipAddress)); String subnet = ipAddress + "/" + prefix; SubnetUtils utils = new SubnetUtils(subnet); String[] addresses = utils.getInfo().getAllAddresses(); for (String addressInSubnet : addresses) { scheduler.execute(new ZWayServerScan(addressInSubnet)); } } } } } } catch (SocketException e) { logger.warn("Error occurred while searching Z-Way servers ({})", e.getMessage()); } }
From source file:org.openhab.binding.vera.internal.discovery.VeraBridgeDiscoveryService.java
private void scan() { logger.debug("Starting scan for Vera controller"); ValidateIPV4 validator = new ValidateIPV4(); try {/*www . j a v a 2 s. c o m*/ Enumeration<NetworkInterface> enumNetworkInterface = NetworkInterface.getNetworkInterfaces(); while (enumNetworkInterface.hasMoreElements()) { NetworkInterface networkInterface = enumNetworkInterface.nextElement(); if (networkInterface.isUp() && !networkInterface.isVirtual() && !networkInterface.isLoopback()) { for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { if (validator.isValidIPV4(address.getAddress().getHostAddress())) { String ipAddress = address.getAddress().getHostAddress(); Short prefix = address.getNetworkPrefixLength(); logger.debug("Scan IP address for Vera Controller: {}", ipAddress); String subnet = ipAddress + "/" + prefix; SubnetUtils utils = new SubnetUtils(subnet); String[] addresses = utils.getInfo().getAllAddresses(); for (String addressInSubnet : addresses) { scheduler.execute(new VeraControllerScan(addressInSubnet)); } } } } } } catch (SocketException e) { logger.warn("Error occurred while searching Vera controller: ", e); } }
From source file:org.openhab.binding.dscalarm.internal.discovery.EnvisalinkBridgeDiscovery.java
/** * Method for Bridge Discovery./* w w w . ja v a 2s .c om*/ */ public synchronized void discoverBridge() { logger.debug("Starting Envisalink Bridge Discovery."); SubnetUtils subnetUtils = null; SubnetInfo subnetInfo = null; long lowIP = 0; long highIP = 0; try { InetAddress localHost = InetAddress.getLocalHost(); NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost); subnetUtils = new SubnetUtils(localHost.getHostAddress() + "/" + networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength()); subnetInfo = subnetUtils.getInfo(); lowIP = convertIPToNumber(subnetInfo.getLowAddress()); highIP = convertIPToNumber(subnetInfo.getHighAddress()); } catch (IllegalArgumentException e) { logger.error("discoverBridge(): Illegal Argument Exception - {}", e.toString()); return; } catch (Exception e) { logger.error("discoverBridge(): Error - Unable to get Subnet Information! {}", e.toString()); return; } logger.debug(" Local IP Address: {} - {}", subnetInfo.getAddress(), convertIPToNumber(subnetInfo.getAddress())); logger.debug(" Subnet: {} - {}", subnetInfo.getNetworkAddress(), convertIPToNumber(subnetInfo.getNetworkAddress())); logger.debug(" Network Prefix: {}", subnetInfo.getCidrSignature().split("/")[1]); logger.debug(" Network Mask: {}", subnetInfo.getNetmask()); logger.debug(" Low IP: {}", convertNumberToIP(lowIP)); logger.debug(" High IP: {}", convertNumberToIP(highIP)); for (long ip = lowIP; ip <= highIP; ip++) { try (Socket socket = new Socket()) { ipAddress = convertNumberToIP(ip); socket.setReuseAddress(true); socket.setReceiveBufferSize(32); socket.connect(new InetSocketAddress(ipAddress, ENVISALINK_BRIDGE_PORT), CONNECTION_TIMEOUT); if (socket.isConnected()) { String message = ""; socket.setSoTimeout(SO_TIMEOUT); try (BufferedReader input = new BufferedReader( new InputStreamReader(socket.getInputStream()))) { message = input.readLine(); } catch (SocketTimeoutException e) { logger.error("discoverBridge(): No Message Read from Socket at [{}] - {}", ipAddress, e.getMessage()); continue; } catch (Exception e) { logger.error("discoverBridge(): Exception Reading from Socket! {}", e.toString()); continue; } if (message.substring(0, 3).equals(ENVISALINK_DISCOVERY_RESPONSE)) { logger.debug("discoverBridge(): Bridge Found - [{}]! Message - '{}'", ipAddress, message); dscAlarmBridgeDiscovery.addEnvisalinkBridge(ipAddress); } else { logger.debug("discoverBridge(): No Response from Connection - [{}]! Message - '{}'", ipAddress, message); } } } catch (IllegalArgumentException e) { logger.error("discoverBridge(): Illegal Argument Exception - {}", e.toString()); } catch (SocketTimeoutException e) { logger.trace("discoverBridge(): No Connection on Port 4025! [{}]", ipAddress); } catch (SocketException e) { logger.error("discoverBridge(): Socket Exception! [{}] - {}", ipAddress, e.toString()); } catch (IOException e) { logger.error("discoverBridge(): IO Exception! [{}] - {}", ipAddress, e.toString()); } } }
From source file:com.hypersocket.client.hosts.HostsFileManager.java
private boolean checkRange(int _8bits, int _16bits, int _24bits) throws SocketException, UnknownHostException { Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface net = e.nextElement(); for (InterfaceAddress i : net.getInterfaceAddresses()) { String range = _8bits + "." + _16bits + "." + _24bits; if (log.isInfoEnabled()) { log.info("Checking interface " + i.toString()); }/*from w ww .ja va2s .c o m*/ if (i.getNetworkPrefixLength() > 0 && i.getNetworkPrefixLength() <= 31) { CIDR c = CIDR4.newCIDR(range + ".0" + "/" + i.getNetworkPrefixLength()); if (c.contains(i.getAddress())) { if (log.isInfoEnabled()) { log.warn(i.getAddress() + " appears to be in our chosen range " + range + ".0" + "/" + i.getNetworkPrefixLength()); } return false; } } } } return true; }
From source file:org.springframework.data.hadoop.util.net.DefaultHostInfoDiscovery.java
@Override public HostInfo getHostInfo() { List<NetworkInterface> interfaces; try {/* w w w. java 2s .c om*/ interfaces = getAllAvailableInterfaces(); } catch (SocketException e) { return null; } // pre filter candidates interfaces = filterInterfaces(interfaces); // sort to prepare getting first match interfaces = sortInterfaces(interfaces); for (NetworkInterface nic : interfaces) { List<InetAddress> addresses = new ArrayList<InetAddress>(); for (InterfaceAddress interfaceAddress : nic.getInterfaceAddresses()) { addresses.add(interfaceAddress.getAddress()); } addresses = filterAddresses(addresses); if (!addresses.isEmpty()) { InetAddress address = addresses.get(0); return new HostInfo(address.getHostAddress(), address.getHostName()); } } return null; }
From source file:it.anyplace.sync.discovery.protocol.ld.LocalDiscorveryHandler.java
public Future sendAnnounceMessage() { return processingExecutorService.submit(new Callable() { @Override/*from w w w. j a v a2 s . c o m*/ public Object call() throws Exception { for (int i = 0; i < 10 && !isListening; i++) { //wait for listening Thread.sleep(100); } if (!isListening) { logger.warn("skipping announce message, udp listening is not active"); return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); new DataOutputStream(out).writeInt(MAGIC); Announce.newBuilder() .setId(ByteString.copyFrom(deviceIdStringToHashData(configuration.getDeviceId()))) .setInstanceId(configuration.getInstanceId()).build().writeTo(out); byte[] data = out.toByteArray(); Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress broadcastAddress = interfaceAddress.getBroadcast(); logger.trace("interface = {} address = {} broadcast = {}", networkInterface, interfaceAddress, broadcastAddress); if (broadcastAddress != null) { logger.debug("sending broadcast announce on {}", broadcastAddress); try (DatagramSocket broadcastSocket = new DatagramSocket()) { broadcastSocket.setBroadcast(true); DatagramPacket datagramPacket = new DatagramPacket(data, data.length, broadcastAddress, UDP_PORT); broadcastSocket.send(datagramPacket); } catch (Exception ex) { logger.warn("error sending datagram", ex); } } } } return null; } }); }
From source file:org.openhab.binding.networkhealth.discovery.NetworkHealthDiscoveryService.java
/** * Gets every IPv4 Address on each Interface except the loopback * The Address format is ip/subnet//from w w w .j ava2s. c o m * @return The collected IPv4 Addresses */ private TreeSet<String> getInterfaceIPs() { TreeSet<String> interfaceIPs = new TreeSet<String>(); try { // For each interface ... for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface networkInterface = en.nextElement(); if (!networkInterface.isLoopback()) { // .. and for each address ... for (Iterator<InterfaceAddress> it = networkInterface.getInterfaceAddresses().iterator(); it .hasNext();) { // ... get IP and Subnet InterfaceAddress interfaceAddress = it.next(); interfaceIPs.add(interfaceAddress.getAddress().getHostAddress() + "/" + interfaceAddress.getNetworkPrefixLength()); } } } } catch (SocketException e) { } return interfaceIPs; }
From source file:org.alfresco.filesys.auth.PassthruServerFactory.java
/** * Set the broadcast mask to use for NetBIOS name lookups * /*w w w . j av a2 s .co m*/ * @param bcastMask String * @exception AlfrescoRuntimeException */ public final void setBroadcastMask(String bcastMask) throws IOException { if (bcastMask == null || bcastMask.length() == 0) { // Clear the NetBIOS subnet mask NetBIOSSession.setDefaultSubnetMask(null); return; } // Find the network adapter with the matching broadcast mask try { Enumeration<NetworkInterface> netEnum = NetworkInterface.getNetworkInterfaces(); NetworkInterface bcastIface = null; while (netEnum.hasMoreElements() && bcastIface == null) { NetworkInterface ni = netEnum.nextElement(); for (InterfaceAddress iAddr : ni.getInterfaceAddresses()) { InetAddress broadcast = iAddr.getBroadcast(); if (broadcast != null && broadcast.getHostAddress().equals(bcastMask)) bcastIface = ni; } } // DEBUG if (logger.isDebugEnabled()) { if (bcastIface != null) logger.debug("Broadcast mask " + bcastMask + " found on network interface " + bcastIface.getDisplayName() + "/" + bcastIface.getName()); else logger.debug("Failed to find network interface for broadcast mask " + bcastMask); } // Check if we found a valid network interface for the broadcast mask if (bcastIface == null) throw new AlfrescoRuntimeException( "Network interface for broadcast mask " + bcastMask + " not found"); // Set the NetBIOS broadcast mask NetBIOSSession.setDefaultSubnetMask(bcastMask); } catch (SocketException ex) { } }
From source file:org.openhab.binding.plclogo.internal.discovery.PLCDiscoveryService.java
@Override protected void startScan() { stopScan();/*from w w w .j a v a 2s .c o m*/ logger.debug("Start scan for LOGO! bridge"); Enumeration<NetworkInterface> devices = null; try { devices = NetworkInterface.getNetworkInterfaces(); } catch (SocketException exception) { logger.warn("LOGO! bridge discovering: {}.", exception.toString()); } Set<String> addresses = new TreeSet<>(); while ((devices != null) && devices.hasMoreElements()) { NetworkInterface device = devices.nextElement(); try { if (!device.isUp() || device.isLoopback()) { continue; } } catch (SocketException exception) { logger.warn("LOGO! bridge discovering: {}.", exception.toString()); } for (InterfaceAddress iface : device.getInterfaceAddresses()) { InetAddress address = iface.getAddress(); if (address instanceof Inet4Address) { String prefix = String.valueOf(iface.getNetworkPrefixLength()); SubnetUtils utilities = new SubnetUtils(address.getHostAddress() + "/" + prefix); addresses.addAll(Arrays.asList(utilities.getInfo().getAllAddresses())); } } } ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); for (String address : addresses) { try { executor.execute(new Runner(address)); } catch (RejectedExecutionException exception) { logger.warn("LOGO! bridge discovering: {}.", exception.toString()); } } try { executor.awaitTermination(CONNECTION_TIMEOUT * addresses.size(), TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { logger.warn("LOGO! bridge discovering: {}.", exception.toString()); } executor.shutdown(); stopScan(); }