java 自动获取广播地址

以下为windows下使用但linux下不能使用:

    NetworkInterface netInterface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
        String broadCastIp = null;
        if (!netInterface.isLoopback()&& netInterface.isUp()) {
            List interfaceAddresses = netInterface.getInterfaceAddresses();
            for (InterfaceAddress interfaceAddress : interfaceAddresses) {
                //只有 IPv4 网络具有广播地址,因此对于 IPv6 网络将返回 null。 
                if(interfaceAddress.getBroadcast()!= null){
                    broadCastIp =interfaceAddress.getBroadcast().getHostAddress();
                }
            }
        }

以下实现不管是windows还是linux都可以用:

/**
     * 获取本机广播地址,并自动区分Windows还是Linux操作系统
     * @return String
     */
    public static String getLocalBroadCast(){
        String broadCastIp = null;
        try {
            Enumeration netInterfaces = (Enumeration) NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) netInterfaces.nextElement();
                if (!netInterface.isLoopback()&& netInterface.isUp()) {
                    List interfaceAddresses = netInterface.getInterfaceAddresses();
                    for (InterfaceAddress interfaceAddress : interfaceAddresses) {
                        //只有 IPv4 网络具有广播地址,因此对于 IPv6 网络将返回 null。 
                        if(interfaceAddress.getBroadcast()!= null){
                            broadCastIp =interfaceAddress.getBroadcast().getHostAddress();

                        }
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        } 
        return broadCastIp;
    }

你可能感兴趣的:(java,网络)