List of usage examples for java.net InterfaceAddress getBroadcast
public InetAddress getBroadcast()
From source file:Main.java
public static void printParameter(NetworkInterface ni) throws SocketException { System.out.println(" Name = " + ni.getName()); System.out.println(" Display Name = " + ni.getDisplayName()); System.out.println(" Is up = " + ni.isUp()); System.out.println(" Support multicast = " + ni.supportsMulticast()); System.out.println(" Is loopback = " + ni.isLoopback()); System.out.println(" Is virtual = " + ni.isVirtual()); System.out.println(" Is point to point = " + ni.isPointToPoint()); System.out.println(" Hardware address = " + ni.getHardwareAddress()); System.out.println(" MTU = " + ni.getMTU()); System.out.println("\nList of Interface Addresses:"); List<InterfaceAddress> list = ni.getInterfaceAddresses(); Iterator<InterfaceAddress> it = list.iterator(); while (it.hasNext()) { InterfaceAddress ia = it.next(); System.out.println(" Address = " + ia.getAddress()); System.out.println(" Broadcast = " + ia.getBroadcast()); System.out.println(" Network prefix length = " + ia.getNetworkPrefixLength()); System.out.println(""); }/*from w w w .j a v a2 s . c om*/ }
From source file:eu.stratosphere.pact.test.util.minicluster.NepheleMiniCluster.java
private static InterfaceAddress getIPInterfaceAddress(boolean preferIPv4) throws Exception, SocketException { final List<InterfaceAddress> interfaces = getNetworkInterface().getInterfaceAddresses(); final Iterator<InterfaceAddress> it = interfaces.iterator(); final List<InterfaceAddress> matchesIPv4 = new ArrayList<InterfaceAddress>(); final List<InterfaceAddress> matchesIPv6 = new ArrayList<InterfaceAddress>(); while (it.hasNext()) { final InterfaceAddress ia = it.next(); if (ia.getBroadcast() != null) { if (ia.getAddress() instanceof Inet4Address) { matchesIPv4.add(ia);/*from ww w.j a v a 2s . c o m*/ } else { matchesIPv6.add(ia); } } } if (matchesIPv4.isEmpty() && matchesIPv6.isEmpty()) { throw new Exception( "Interface " + getNetworkInterface().getName() + " has no interface address attached."); } if (preferIPv4 && !matchesIPv4.isEmpty()) { for (InterfaceAddress ia : matchesIPv4) { if ((ia.getAddress().toString().contains("192") || ia.getAddress().toString().contains("10"))) { return ia; } } return matchesIPv4.get(0); } return !matchesIPv6.isEmpty() ? matchesIPv6.get(0) : matchesIPv4.get(0); }
From source file:com.t_oster.visicut.misc.Helper.java
public static List<String> findVisiCamInstances() { List<String> result = new LinkedList<String>(); // Find the server using UDP broadcast try {/* ww w.j a va 2s . c om*/ //Open a random port to send the package DatagramSocket c = new DatagramSocket(); c.setBroadcast(true); byte[] sendData = "VisiCamDiscover".getBytes(); //Try the 255.255.255.255 first try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 8888); c.send(sendPacket); } catch (Exception e) { } // 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; // Don't want to broadcast to the loopback interface } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); if (broadcast == null) { continue; } // Send the broadcast package! try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888); c.send(sendPacket); } catch (Exception e) { } } } //Wait for a response byte[] recvBuf = new byte[15000]; c.setSoTimeout(3000); while (true) { DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); try { c.receive(receivePacket); //Check if the message is correct String message = new String(receivePacket.getData()).trim(); //Close the port! c.close(); if (message.startsWith("http")) { result.add(message); } } catch (SocketTimeoutException e) { break; } } } catch (IOException ex) { } return result; }
From source file:com.chiralBehaviors.slp.hive.configuration.BroadcastConfiguration.java
InetSocketAddress getBroadcastAddress(NetworkInterface networkInterface) { InetSocketAddress broadcastAddress = null; for (InterfaceAddress addr : networkInterface.getInterfaceAddresses()) { if (ipv4) { if (addr.getBroadcast() != null && addr.getBroadcast().getAddress().length == 4) { broadcastAddress = new InetSocketAddress(addr.getBroadcast(), port); break; }/*from w w w.java 2s .com*/ } else { if (addr.getBroadcast() != null && addr.getBroadcast().getAddress().length > 4) { broadcastAddress = new InetSocketAddress(addr.getBroadcast(), port); break; } } } return broadcastAddress; }
From source file:it.anyplace.sync.discovery.protocol.ld.LocalDiscorveryHandler.java
public Future sendAnnounceMessage() { return processingExecutorService.submit(new Callable() { @Override//from www . j a va 2 s . co 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:gov.nrel.bacnet.consumer.BACnet.java
private void initialize(Config config) throws IOException { LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(1000); RejectedExecutionHandler rejectedExec = new RejectedExecHandler(); // schedule polling on single threaded service because local device instance is not threadsafe execSvc = Executors.newFixedThreadPool(config.getNumThreads()); //give databus recording 2 threads to match old code recorderSvc = new ThreadPoolExecutor(20, 20, 120, TimeUnit.SECONDS, queue, rejectedExec); schedSvc = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(config.getNumThreads()); exec = new OurExecutor(schedSvc, execSvc, recorderSvc); String devname = config.getNetworkDevice(); int device_id = config.getDeviceId(); NetworkInterface networkinterface = null; try {/*from w w w. j a v a 2 s . c o m*/ networkinterface = java.net.NetworkInterface.getByName(devname); } catch (Exception ex) { System.out.println("Unable to open device: " + devname); System.exit(-1); } if (networkinterface == null) { System.out.println("Unable to open device: " + devname); System.exit(-1); } List<InterfaceAddress> addresses = networkinterface.getInterfaceAddresses(); String sbroadcast = null; String saddress = null; //InterfaceAddress ifaceaddr = null; for (InterfaceAddress address : addresses) { logger.fine("Evaluating address: " + address.toString()); if (address.getAddress().getAddress().length == 4) { logger.info("Address is ipv4, selecting: " + address.toString()); sbroadcast = address.getBroadcast().toString().substring(1); saddress = address.getAddress().toString().substring(1); //ifaceaddr = address; break; } else { logger.info("Address is not ipv4, not selecting: " + address.toString()); } } logger.info("Binding to: " + saddress + " " + sbroadcast); localDevice = new LocalDevice(device_id, sbroadcast); localDevice.setPort(LocalDevice.DEFAULT_PORT); localDevice.setTimeout(localDevice.getTimeout() * 3); localDevice.setSegTimeout(localDevice.getSegTimeout() * 3); try { localDevice.initialize(); localDevice.setRetries(0); //don't retry as it seems to really be a waste. } catch (IOException e) { e.printStackTrace(); return; } if (config.getSlaveDeviceEnabled()) { slaveDeviceTimer = new Timer(); slaveDeviceTimer.schedule(new gov.nrel.bacnet.SlaveDevice(localDevice, config), 1000, config.getSlaveDeviceUpdateInterval() * 1000); } int counter = 0; String username = config.getDatabusUserName(); String key = config.getDatabusKey(); logger.info("user=" + username + " key=" + key); DatabusSender sender = null; if (config.getDatabusEnabled()) { sender = new DatabusSender(username, key, execSvc, config.getDatabusUrl(), config.getDatabusPort(), true); } logger.info("databus sender: " + sender); writer = new DatabusDataWriter(new DataPointWriter(sender)); logger.info("databus writer" + writer); }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Returns the set of broadcast addresses available to the network interfaces of this host. In case of IPv6 the set * contains the IPv6 multicast address to reach all nodes on the local link. Moreover, all addresses of the loopback * interfaces are added to the set./*ww w .j a va 2s. c o m*/ * * @return (possibly empty) set of broadcast addresses reachable by this host */ private static Set<InetAddress> getBroadcastAddresses() { final Set<InetAddress> broadcastAddresses = new HashSet<InetAddress>(); // get all network interfaces Enumeration<NetworkInterface> ie = null; try { ie = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { LOG.error("Could not collect network interfaces of host", e); return broadcastAddresses; } while (ie.hasMoreElements()) { NetworkInterface nic = ie.nextElement(); try { if (!nic.isUp()) { continue; } if (nic.isLoopback()) { for (InterfaceAddress adr : nic.getInterfaceAddresses()) { broadcastAddresses.add(adr.getAddress()); } } else { // check all IPs bound to network interfaces for (InterfaceAddress adr : nic.getInterfaceAddresses()) { if (adr == null) { continue; } // collect all broadcast addresses if (USE_IPV6) { try { final InetAddress interfaceAddress = adr.getAddress(); if (interfaceAddress instanceof Inet6Address) { final Inet6Address ipv6Address = (Inet6Address) interfaceAddress; final InetAddress multicastAddress = InetAddress.getByName(IPV6MULTICASTADDRESS + "%" + Integer.toString(ipv6Address.getScopeId())); broadcastAddresses.add(multicastAddress); } } catch (UnknownHostException e) { LOG.error(e); } } else { final InetAddress broadcast = adr.getBroadcast(); if (broadcast != null) { broadcastAddresses.add(broadcast); } } } } } catch (SocketException e) { LOG.error("Socket exception when checking " + nic.getName() + ". " + "Ignoring this device.", e); } } return broadcastAddresses; }
From source file:com.vuze.plugin.azVPN_Helper.CheckerCommon.java
public int getNetworkPrefixLength(NetworkInterface networkInterface, InetAddress address) { int networkPrefixLength = -1; List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses(); for (InterfaceAddress interfaceAddress : interfaceAddresses) { if (!interfaceAddress.getAddress().equals(address)) { continue; }/* ww w. jav a 2 s . c o m*/ networkPrefixLength = interfaceAddress.getNetworkPrefixLength(); // JDK-7107883 : getNetworkPrefixLength() does not return correct prefix length // networkPrefixLength will be zero on Java <= 7 when there is no // Broadcast address. // I'm guessing there is no broadcast address returned when mask is 32 // on linux, but I can't confirm (I've seen it though) if (networkPrefixLength == 0 && interfaceAddress.getBroadcast() == null) { networkPrefixLength = 32; } } return networkPrefixLength; }
From source file:org.alfresco.filesys.auth.PassthruServerFactory.java
/** * Set the broadcast mask to use for NetBIOS name lookups * //from ww w . java 2s . c om * @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.cc86.MMC.client.Main.java
public static String serverDiscovery() { String res = "0.0.0.0"; DatagramSocket c;//from www. j ava 2 s. co m // Find the server using UDP broadcast try { //Open a random port to send the package c = new DatagramSocket(); c.setBroadcast(true); byte[] sendData = "DISCOVER_MMC_REQUEST".getBytes(); //Try the 255.255.255.255 first try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 0xCC86); c.send(sendPacket); l.info("Request packet sent to: 255.255.255.255 (DEFAULT)"); } catch (Exception e) { } // Broadcast the message over all the network interfaces Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; // Don't want to broadcast to the loopback interface } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); if (broadcast == null) { continue; } // Send the broadcast package! try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888); c.send(sendPacket); } catch (Exception e) { } l.info("Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName()); } } l.info("Done looping over all network interfaces. Now waiting for a reply!"); //Wait for a response byte[] recvBuf = new byte[15000]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); c.receive(receivePacket); //We have a response l.info("Broadcast response from server: " + receivePacket.getAddress().getHostAddress()); //Check if the message is correct String message = new String(receivePacket.getData()).trim(); if (message.equals("DISCOVER_MMC_RESPONSE")) { //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller) res = (receivePacket.getAddress() + "").substring(1); } //Close the port! c.close(); } catch (IOException ex) { } return res; }