Java Code Examples for java.net.InterfaceAddress#getBroadcast()

The following examples show how to use java.net.InterfaceAddress#getBroadcast() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NetWorkUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 获取广播 IP 地址
 * @return 广播 IP 地址
 */
public static String getBroadcastIpAddress() {
    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        while (nis.hasMoreElements()) {
            NetworkInterface ni = nis.nextElement();
            if (!ni.isUp() || ni.isLoopback()) continue;
            List<InterfaceAddress> ias = ni.getInterfaceAddresses();
            for (int i = 0; i < ias.size(); i++) {
                InterfaceAddress ia = ias.get(i);
                InetAddress broadcast = ia.getBroadcast();
                if (broadcast != null) {
                    return broadcast.getHostAddress();
                }
            }
        }
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getBroadcastIpAddress");
    }
    return null;
}
 
Example 2
Source File: StorageUtils.java    From incubator-crail with Apache License 2.0 6 votes vote down vote up
public static InetSocketAddress getDataNodeAddress(String ifname, int port) throws IOException {
	NetworkInterface netif = NetworkInterface.getByName(ifname);
	if (netif == null){
		throw new IOException("Cannot find network interface with name " + ifname);
	}
	List<InterfaceAddress> addresses = netif.getInterfaceAddresses();
	InetAddress addr = null;
	for (InterfaceAddress address: addresses){
		if (address.getBroadcast() != null){
			InetAddress _addr = address.getAddress();
			addr = _addr;
		}
	}

	if (addr == null){
		throw new IOException("Network interface with name " + ifname + " has no valid IP address");
	}
	InetSocketAddress inetAddr = new InetSocketAddress(addr, port);
	return inetAddr;
}
 
Example 3
Source File: Tools.java    From AndroidDemo with MIT License 6 votes vote down vote up
public static String getBroadcast() {
    System.setProperty("java.net.preferIPv4Stack", "true");
    try {
        for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum.hasMoreElements(); ) {
            NetworkInterface ni = niEnum.nextElement();
            if (ni.getName().toLowerCase().equals("wlan0")) {
                if (!ni.isLoopback()) {
                    for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
                        if (interfaceAddress.getBroadcast() != null) {
                            return interfaceAddress.getBroadcast().toString().substring(1);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        //
    }
    return null;
}
 
Example 4
Source File: SsdpDiscovery.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private static List<InetAddress> getBroadCastAddress() throws Exception {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    List<InetAddress> addresses = new ArrayList<InetAddress>();
    addresses.add(InetAddress.getByName("255.255.255.255"));
    while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = interfaces.nextElement();
        if (networkInterface.isLoopback() || !networkInterface.supportsMulticast()) {
            continue; // Don't want to broadcast to the loopback interface
        }
        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
            InetAddress broadcast = interfaceAddress.getBroadcast();
            if (broadcast != null) {
                addresses.add(broadcast);
            }
        }
    }
    return addresses;
}
 
Example 5
Source File: WifiUtils.java    From WifiChat with GNU General Public License v2.0 6 votes vote down vote up
public static String getBroadcastAddress() {
    System.setProperty("java.net.preferIPv4Stack", "true");
    try {
        for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum
                .hasMoreElements();) {
            NetworkInterface ni = niEnum.nextElement();
            if (!ni.isLoopback()) {
                for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
                    if (interfaceAddress.getBroadcast() != null) {
                        logger.d(interfaceAddress.getBroadcast().toString().substring(1));
                        return interfaceAddress.getBroadcast().toString().substring(1);
                    }
                }
            }
        }
    }
    catch (SocketException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 6
Source File: DesktopHostsActivity.java    From deskcon-android with GNU General Public License v3.0 6 votes vote down vote up
public static InetAddress getBroadcast(){
InetAddress found_bcast_address=null;
 System.setProperty("java.net.preferIPv4Stack", "true"); 
    try
    {
      Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces();
      while (niEnum.hasMoreElements())
      {
        NetworkInterface ni = niEnum.nextElement();
        if(!ni.isLoopback()){
            for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses())
            {
              found_bcast_address = interfaceAddress.getBroadcast();               
            }
        }
      }
    }
    catch (SocketException e)
    {
      e.printStackTrace();
    }

    return found_bcast_address;
}
 
Example 7
Source File: BroadcastUtils.java    From samba-documents-provider with GNU General Public License v3.0 6 votes vote down vote up
static List<String> getBroadcastAddress() throws BrowsingException, SocketException {
  Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

  List<String> broadcastAddresses = new ArrayList<>();

  while (interfaces.hasMoreElements()) {
    NetworkInterface networkInterface = interfaces.nextElement();
    if (networkInterface.isLoopback()) {
      continue;
    }

    for (InterfaceAddress interfaceAddress :
            networkInterface.getInterfaceAddresses()) {
      InetAddress broadcast = interfaceAddress.getBroadcast();

      if (broadcast != null) {
        broadcastAddresses.add(broadcast.toString().substring(1));
      }
    }
  }

  return broadcastAddresses;
}
 
Example 8
Source File: NetworkUtils.java    From AndroidUtilCode with Apache License 2.0 6 votes vote down vote up
/**
 * Return the ip address of broadcast.
 *
 * @return the ip address of broadcast
 */
public static String getBroadcastIpAddress() {
    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        LinkedList<InetAddress> adds = new LinkedList<>();
        while (nis.hasMoreElements()) {
            NetworkInterface ni = nis.nextElement();
            if (!ni.isUp() || ni.isLoopback()) continue;
            List<InterfaceAddress> ias = ni.getInterfaceAddresses();
            for (int i = 0, size = ias.size(); i < size; i++) {
                InterfaceAddress ia = ias.get(i);
                InetAddress broadcast = ia.getBroadcast();
                if (broadcast != null) {
                    return broadcast.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 9
Source File: TcpStorageServer.java    From crail with Apache License 2.0 6 votes vote down vote up
public static InetSocketAddress getDataNodeAddress() throws IOException {
	String ifname = TcpStorageConstants.STORAGE_TCP_INTERFACE;
	int port = TcpStorageConstants.STORAGE_TCP_PORT;
	
	NetworkInterface netif = NetworkInterface.getByName(ifname);
	if (netif == null){
		return null;
	}
	List<InterfaceAddress> addresses = netif.getInterfaceAddresses();
	InetAddress addr = null;
	for (InterfaceAddress address: addresses){
		if (address.getBroadcast() != null){
			InetAddress _addr = address.getAddress();
			addr = _addr;
		}
	}		
	InetSocketAddress inetAddr = new InetSocketAddress(addr, port);
	return inetAddr;
}
 
Example 10
Source File: RdmaStorageServer.java    From crail with Apache License 2.0 6 votes vote down vote up
public static InetSocketAddress getDataNodeAddress() throws IOException {
		String ifname = RdmaConstants.STORAGE_RDMA_INTERFACE;
		int port = RdmaConstants.STORAGE_RDMA_PORT;
		
		NetworkInterface netif = NetworkInterface.getByName(ifname);
		if (netif == null){
			return null;
		}
		List<InterfaceAddress> addresses = netif.getInterfaceAddresses();
		InetAddress addr = null;
		for (InterfaceAddress address: addresses){
//			LOG.info("address* " + address.toString() + ", _addr " + _addr.toString() + ", isSiteLocal " + _addr.isSiteLocalAddress() + ", tmp " + tmp + ", size " + tmp.length + ", broadcast " + address.getBroadcast());
			if (address.getBroadcast() != null){
				InetAddress _addr = address.getAddress();
				addr = _addr;
			}
		}		
		InetSocketAddress inetAddr = new InetSocketAddress(addr, port);
		return inetAddr;
	}
 
Example 11
Source File: WifiUtils.java    From FlyWoo with Apache License 2.0 6 votes vote down vote up
public static String getBroadcastAddress() {
    System.setProperty("java.net.preferIPv4Stack", "true");
    try {
        for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum
                .hasMoreElements(); ) {
            NetworkInterface ni = niEnum.nextElement();
            if (!ni.isLoopback()) {
                for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
                    if (interfaceAddress.getBroadcast() != null) {
                        L.d(TAG, interfaceAddress.getBroadcast().toString().substring(1));
                        return interfaceAddress.getBroadcast().toString().substring(1);
                    }
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 12
Source File: NetUtil.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Get all broadcast addresses on the current host
 *
 * @return list of broadcast addresses, empty list if no broadcast addresses found
 */
public static List<String> getAllBroadcastAddresses() {
    List<String> broadcastAddresses = new LinkedList<>();
    try {
        final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            final NetworkInterface networkInterface = networkInterfaces.nextElement();
            final List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
            for (InterfaceAddress interfaceAddress : interfaceAddresses) {
                final InetAddress addr = interfaceAddress.getAddress();
                if (addr instanceof Inet4Address && !addr.isLinkLocalAddress() && !addr.isLoopbackAddress()) {
                    InetAddress broadcast = interfaceAddress.getBroadcast();
                    if (broadcast != null) {
                        broadcastAddresses.add(broadcast.getHostAddress());
                    }
                }
            }
        }
    } catch (SocketException ex) {
        LOGGER.error("Could not find broadcast address: {}", ex.getMessage(), ex);
    }
    return broadcastAddresses;
}
 
Example 13
Source File: MainActivity.java    From ForgePE with GNU Affero General Public License v3.0 6 votes vote down vote up
public String[] getBroadcastAddresses() {
    ArrayList<String> list = new ArrayList<>();
    try {
        System.setProperty("java.net.preferIPv4Stack", "true");
        Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces();

        while (niEnum.hasMoreElements()) {
            NetworkInterface ni = niEnum.nextElement();

            if (!ni.isLoopback()) {
                for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
                    if (interfaceAddress.getBroadcast() != null)
                        list.add(interfaceAddress.getBroadcast().toString().substring(1));
                }
            }
        }
    } catch (Exception ignored) {
    }
    return list.toArray(new String[list.size()]);
}
 
Example 14
Source File: NetUtil.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Get all broadcast addresses on the current host
 *
 * @return list of broadcast addresses, empty list if no broadcast addresses found
 */
public static List<String> getAllBroadcastAddresses() {
    List<String> broadcastAddresses = new LinkedList<String>();
    try {
        final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            final NetworkInterface networkInterface = networkInterfaces.nextElement();
            final List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
            for (InterfaceAddress interfaceAddress : interfaceAddresses) {
                final InetAddress addr = interfaceAddress.getAddress();
                if (addr instanceof Inet4Address && !addr.isLinkLocalAddress() && !addr.isLoopbackAddress()) {
                    InetAddress broadcast = interfaceAddress.getBroadcast();
                    if (broadcast != null) {
                        broadcastAddresses.add(broadcast.getHostAddress());
                    }
                }
            }
        }
    } catch (SocketException ex) {
        LOGGER.error("Could not find broadcast address: {}", ex.getMessage(), ex);
    }
    return broadcastAddresses;
}
 
Example 15
Source File: IfConfig.java    From crate with Apache License 2.0 5 votes vote down vote up
/** format internet address: java's default doesn't include everything useful */
private static String formatAddress(InterfaceAddress interfaceAddress) throws IOException {
    StringBuilder sb = new StringBuilder();

    InetAddress address = interfaceAddress.getAddress();
    if (address instanceof Inet6Address) {
        sb.append("inet6 ");
        sb.append(NetworkAddress.format(address));
        sb.append(" prefixlen:");
        sb.append(interfaceAddress.getNetworkPrefixLength());
    } else {
        sb.append("inet ");
        sb.append(NetworkAddress.format(address));
        int netmask = 0xFFFFFFFF << (32 - interfaceAddress.getNetworkPrefixLength());
        sb.append(" netmask:").append(NetworkAddress.format(InetAddress.getByAddress(new byte[]{
            (byte) (netmask >>> 24),
            (byte) (netmask >>> 16 & 0xFF),
            (byte) (netmask >>> 8 & 0xFF),
            (byte) (netmask & 0xFF)
        })));
        InetAddress broadcast = interfaceAddress.getBroadcast();
        if (broadcast != null) {
            sb.append(" broadcast:").append(NetworkAddress.format(broadcast));
        }
    }
    if (address.isLoopbackAddress()) {
        sb.append(" scope:host");
    } else if (address.isLinkLocalAddress()) {
        sb.append(" scope:link");
    } else if (address.isSiteLocalAddress()) {
        sb.append(" scope:site");
    }
    return sb.toString();
}
 
Example 16
Source File: NetworkAddressFactoryImpl.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public InetAddress getBroadcastAddress(InetAddress inetAddress) {
    synchronized (networkInterfaces) {
        for (NetworkInterface iface : networkInterfaces) {
            for (InterfaceAddress interfaceAddress : getInterfaceAddresses(iface)) {
                if (interfaceAddress != null && interfaceAddress.getAddress().equals(inetAddress)) {
                    return interfaceAddress.getBroadcast();
                }
            }
        }
    }
    return null;
}
 
Example 17
Source File: UDPLocator.java    From moleculer-java with MIT License 5 votes vote down vote up
protected void startReceivers(NetworkInterface ni, String udpMulticast, boolean udpBroadcast) throws Exception {
	if (ni == null || ni.isLoopback()) {
		return;
	}
	List<InterfaceAddress> list = ni.getInterfaceAddresses();
	if (list == null || list.isEmpty()) {
		return;
	}
	if (udpMulticast != null && ni.supportsMulticast()) {

		// Create multicast receiver
		receivers.add(new UDPMulticastReceiver(nodeID, udpMulticast, transporter, ni));
	}
	if (udpBroadcast) {
		for (InterfaceAddress ia : list) {
			if (ia == null) {
				continue;
			}
			InetAddress address = ia.getBroadcast();
			if (address == null || address.isLoopbackAddress()) {
				continue;
			}
			String udpAddress = address.getHostAddress();
			if (udpAddress == null || udpAddress.isEmpty() || udpAddress.startsWith("127.")) {
				continue;
			}

			// Create broadcast receiver
			receivers.add(new UDPBroadcastReceiver(nodeID, udpAddress, transporter));
		}
	}
}
 
Example 18
Source File: IfConfig.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/** format internet address: java's default doesn't include everything useful */
private static String formatAddress(InterfaceAddress interfaceAddress) throws IOException {
    StringBuilder sb = new StringBuilder();
    
    InetAddress address = interfaceAddress.getAddress();
    if (address instanceof Inet6Address) {
        sb.append("inet6 ");
        sb.append(NetworkAddress.formatAddress(address));
        sb.append(" prefixlen:");
        sb.append(interfaceAddress.getNetworkPrefixLength());
    } else {
        sb.append("inet ");
        sb.append(NetworkAddress.formatAddress(address));
        int netmask = 0xFFFFFFFF << (32 - interfaceAddress.getNetworkPrefixLength());
        sb.append(" netmask:" + NetworkAddress.formatAddress(InetAddress.getByAddress(new byte[] {
                (byte)(netmask >>> 24), 
                (byte)(netmask >>> 16 & 0xFF), 
                (byte)(netmask >>> 8 & 0xFF), 
                (byte)(netmask & 0xFF) 
        })));
        InetAddress broadcast = interfaceAddress.getBroadcast();
        if (broadcast != null) {
            sb.append(" broadcast:" + NetworkAddress.formatAddress(broadcast));
        }
    }
    if (address.isLoopbackAddress()) {
        sb.append(" scope:host");
    } else if (address.isLinkLocalAddress()) {
        sb.append(" scope:link");
    } else if (address.isSiteLocalAddress()) {
        sb.append(" scope:site");
    }
    return sb.toString();
}
 
Example 19
Source File: NetworkAddressFactoryImpl.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
public InetAddress getBroadcastAddress(InetAddress inetAddress) {
    synchronized (networkInterfaces) {
        for (NetworkInterface iface : networkInterfaces) {
            for (InterfaceAddress interfaceAddress : getInterfaceAddresses(iface)) {
                if (interfaceAddress != null && interfaceAddress.getAddress().equals(inetAddress)) {
                    return interfaceAddress.getBroadcast();
                }
            }
        }
    }
    return null;
}
 
Example 20
Source File: HostNewworkInfo.java    From uavstack with Apache License 2.0 4 votes vote down vote up
/**
 * @return {wlan0={ips={"192.168.1.109":{"bcast":"192.168.1.255","mask":"255.255.255.0"}}, mac=28:C6:3F:C4:29:23}}
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Map getNetCardInfo() {

    Map netCardInfos = new HashMap<String, Map<String, String>>();
    Enumeration<NetworkInterface> netInterfaces;
    try {
        netInterfaces = NetworkInterface.getNetworkInterfaces();
        while (netInterfaces.hasMoreElements()) {
            NetworkInterface ni = netInterfaces.nextElement();
            // if (ni.isVirtual()) {
            // continue;
            // }

            Map ipInfos = new HashMap<String, Map<String, String>>();
            List<InterfaceAddress> addresses = ni.getInterfaceAddresses();
            for (InterfaceAddress ia : addresses) {
                if (ia.getAddress().isLoopbackAddress() || ia.getAddress().getHostAddress().indexOf(":") != -1) {
                    continue;
                }

                Map ipInfo = new HashMap<String, String>();

                InetAddress bcast = ia.getBroadcast();
                ipInfo.put("bcast", bcast == null ? "UNKNOWN" : bcast.getHostAddress());
                ipInfo.put("mask", NetmaskLengthToNetmask(ia.getNetworkPrefixLength()));

                ipInfos.put(ia.getAddress().getHostAddress(), ipInfo);
            }

            if (!ipInfos.isEmpty()) {
                Map netCardInfo = new HashMap<String, Map<String, String>>();
                netCardInfo.put("ips", JSONHelper.toString(ipInfos));
                netCardInfo.put("mac", getMacAddressAsString(ni));
                netCardInfos.put(ni.getName(), netCardInfo);
            }
        }
    }
    catch (SocketException e) {
        // ignore
    }

    return netCardInfos;
}