當前位置: 首頁>>代碼示例>>Java>>正文


Java InterfaceAddress.getNetworkPrefixLength方法代碼示例

本文整理匯總了Java中java.net.InterfaceAddress.getNetworkPrefixLength方法的典型用法代碼示例。如果您正苦於以下問題:Java InterfaceAddress.getNetworkPrefixLength方法的具體用法?Java InterfaceAddress.getNetworkPrefixLength怎麽用?Java InterfaceAddress.getNetworkPrefixLength使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.net.InterfaceAddress的用法示例。


在下文中一共展示了InterfaceAddress.getNetworkPrefixLength方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: main

import java.net.InterfaceAddress; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
    Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();

    while (nics.hasMoreElements()) {
        NetworkInterface nic = nics.nextElement();
        for (InterfaceAddress iaddr : nic.getInterfaceAddresses()) {
            boolean valid = checkPrefix(iaddr);
            if (!valid) {
                passed = false;
                debug(nic.getName(), iaddr);
            }
            InetAddress ia = iaddr.getAddress();
            if (ia.isLoopbackAddress() && ia instanceof Inet4Address) {
                // assumption: prefix length will always be 8
                if (iaddr.getNetworkPrefixLength() != 8) {
                    out.println("Expected prefix of 8, got " + iaddr);
                    passed = false;
                }
            }
        }
    }

    if (!passed)
        throw new RuntimeException("Failed: some interfaces have invalid prefix lengths");
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:26,代碼來源:NetworkPrefixLength.java

示例2: getLocalCidrs

import java.net.InterfaceAddress; //導入方法依賴的package包/類
public static String[] getLocalCidrs() {
    final String defaultHostIp = getDefaultHostIp();

    final List<String> cidrList = new ArrayList<>();
    try {
        for (final NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
            if (ifc.isUp() && !ifc.isVirtual() && !ifc.isLoopback()) {
                for (final InterfaceAddress address : ifc.getInterfaceAddresses()) {
                    final InetAddress addr = address.getAddress();
                    final int prefixLength = address.getNetworkPrefixLength();
                    if (prefixLength < MAX_CIDR && prefixLength > 0) {
                        final String ip = addr.getHostAddress();
                        if (ip.equalsIgnoreCase(defaultHostIp)) {
                            cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength)));
                        }
                    }
                }
            }
        }
    } catch (final SocketException e) {
        s_logger.warn("UnknownHostException in getLocalCidrs().", e);
    }

    return cidrList.toArray(new String[0]);
}
 
開發者ID:MissionCriticalCloud,項目名稱:cosmic,代碼行數:26,代碼來源:NetUtils.java

示例3: firstLocalNonLoopbackIpv4Address

import java.net.InterfaceAddress; //導入方法依賴的package包/類
/**
 * @deprecated This method is no longer used by LittleProxy and may be removed in a future release.
 */
@Deprecated
public static InetAddress firstLocalNonLoopbackIpv4Address() {
    try {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
                .getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces
                    .nextElement();
            if (networkInterface.isUp()) {
                for (InterfaceAddress ifAddress : networkInterface
                        .getInterfaceAddresses()) {
                    if (ifAddress.getNetworkPrefixLength() > 0
                            && ifAddress.getNetworkPrefixLength() <= 32
                            && !ifAddress.getAddress().isLoopbackAddress()) {
                        return ifAddress.getAddress();
                    }
                }
            }
        }
        return null;
    } catch (SocketException se) {
        return null;
    }
}
 
開發者ID:wxyzZ,項目名稱:little_mitm,代碼行數:28,代碼來源:NetworkUtils.java

示例4: firstLocalNonLoopbackIpv4Address

import java.net.InterfaceAddress; //導入方法依賴的package包/類
/**
 * Go through our network interfaces and find the first bound address for an
 * up interface that's in the IPv4 address space and is not the loopback
 * address.
 * 
 * @return
 */
public static InetAddress firstLocalNonLoopbackIpv4Address() {
    try {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
                .getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces
                    .nextElement();
            if (networkInterface.isUp()) {
                for (InterfaceAddress ifAddress : networkInterface
                        .getInterfaceAddresses()) {
                    if (ifAddress.getNetworkPrefixLength() > 0
                            && ifAddress.getNetworkPrefixLength() <= 32
                            && !ifAddress.getAddress().isLoopbackAddress()) {
                        return ifAddress.getAddress();
                    }
                }
            }
        }
        return null;
    } catch (SocketException se) {
        return null;
    }
}
 
開發者ID:Elitward,項目名稱:LittleProxy,代碼行數:31,代碼來源:NetworkUtils.java

示例5: getMask

import java.net.InterfaceAddress; //導入方法依賴的package包/類
public static String getMask(String intf){
    try {
        NetworkInterface ntwrk = NetworkInterface.getByName(intf);
        Iterator<InterfaceAddress> addrList = ntwrk.getInterfaceAddresses().iterator();
        while (addrList.hasNext()) {
            InterfaceAddress addr = addrList.next();
            InetAddress ip = addr.getAddress();
            if (ip instanceof Inet4Address) {
                String mask = ip.getHostAddress() + "/" +
                        addr.getNetworkPrefixLength();
                return mask;
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
 
開發者ID:EthACKdotOrg,項目名稱:orWall,代碼行數:19,代碼來源:NetworkHelper.java

示例6: setIpInfoFromNetworkInterface

import java.net.InterfaceAddress; //導入方法依賴的package包/類
private void setIpInfoFromNetworkInterface() {
    try {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        if (networkInterfaces == null) {
            return;
        }
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface netIf = networkInterfaces.nextElement();

            for (Enumeration<InetAddress> inetAddresses = netIf.getInetAddresses(); inetAddresses.hasMoreElements();) {
                InetAddress inetAddress = inetAddresses.nextElement();
                if (inetAddress.isLoopbackAddress() || inetAddress instanceof Inet6Address) {
                    continue;
                }
                if (netIf.getDisplayName().contains("wlan0")
                        || netIf.getDisplayName().contains("eth0")
                        || netIf.getDisplayName().contains("ap0")) {
                    FDroidApp.ipAddressString = inetAddress.getHostAddress();
                    for (InterfaceAddress address : netIf.getInterfaceAddresses()) {
                        short networkPrefixLength = address.getNetworkPrefixLength();
                        if (networkPrefixLength > 32) {
                            // something is giving a "/64" netmask, IPv6?
                            // java.lang.IllegalArgumentException: Value [64] not in range [0,32]
                            continue;
                        }
                        if (inetAddress.equals(address.getAddress()) && !TextUtils.isEmpty(FDroidApp.ipAddressString)) {
                            String cidr = String.format(Locale.ENGLISH, "%s/%d",
                                    FDroidApp.ipAddressString, networkPrefixLength);
                            FDroidApp.subnetInfo = new SubnetUtils(cidr).getInfo();
                            break;
                        }
                    }
                }
            }
        }
    } catch (SocketException e) {
        Log.e(TAG, "Could not get ip address", e);
    }
}
 
開發者ID:uhuru-mobile,項目名稱:mobile-store,代碼行數:40,代碼來源:WifiStateChangeService.java

示例7: formatAddress

import java.net.InterfaceAddress; //導入方法依賴的package包/類
/** 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:" + 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:" + 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();
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:35,代碼來源:IfConfig.java

示例8: formatAddress

import java.net.InterfaceAddress; //導入方法依賴的package包/類
/** 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();
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:35,代碼來源:IfConfig.java

示例9: findIpRanges

import java.net.InterfaceAddress; //導入方法依賴的package包/類
/**
 * Finds all IP ranges of the network interfaces which the local machine has
 * 
 * @return array list of ip ranges in CIDR notation
 * @throws UnknownHostException
 * @throws SocketException
 */
public static List<String> findIpRanges() throws UnknownHostException, SocketException {

	ArrayList<String> ipRanges = new ArrayList<String>();

	// Find all IP ranges of network interfaces belonging to the local
	// machine.
	// (It may have multiple network interfaces, therefore might have
	// multiple IP addresses)
	Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
	while (netInterfaces.hasMoreElements()) {
		// http://bugs.java.com/view_bug.do?bug_id=6707289
		NetworkInterface iface = netInterfaces.nextElement();
		if (!iface.getName().contains("lo")) { // Consider only eth
												// networks, skip localhost
			for (InterfaceAddress ifaceAddress : iface.getInterfaceAddresses()) {
				if (ifaceAddress.getNetworkPrefixLength() <= (short) 32) {
					SubnetUtils subnet = new SubnetUtils(ifaceAddress.getAddress().getHostAddress() + "/"
							+ ifaceAddress.getNetworkPrefixLength());
					String ipRange = subnet.getInfo().getLowAddress() + "/" + ifaceAddress.getNetworkPrefixLength();
					ipRanges.add(ipRange);

					logger.info("iface " + iface.getName() + " has address " + ifaceAddress.getAddress() + "/"
							+ ifaceAddress.getNetworkPrefixLength());
				}
			}
		}
	}

	logger.info("IP ranges have been found. Returning results.");

	return ipRanges;
}
 
開發者ID:Pardus-LiderAhenk,項目名稱:lider-ahenk-installer,代碼行數:40,代碼來源:NetworkUtils.java

示例10: sameNetwork

import java.net.InterfaceAddress; //導入方法依賴的package包/類
public static boolean sameNetwork(String localAddress, String remoteAddress)
    throws Exception {
    InetAddress addr = InetAddress.getByName(localAddress);
    NetworkInterface networkInterface = NetworkInterface.getByInetAddress(addr);
    short netmask = -1;
    for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
        if (address.getAddress().equals(addr)) {
            netmask = address.getNetworkPrefixLength();
        }
    }
    return sameNetwork(localAddress, netmask, remoteAddress);
}
 
開發者ID:SignalK,項目名稱:signalk-core-java,代碼行數:13,代碼來源:Util.java

示例11: getAddressNetworkPrefixLength

import java.net.InterfaceAddress; //導入方法依賴的package包/類
public Short getAddressNetworkPrefixLength(InetAddress inetAddress) {
    synchronized (networkInterfaces) {
        for (NetworkInterface iface : networkInterfaces) {
            for (InterfaceAddress interfaceAddress : getInterfaceAddresses(iface)) {
                if (interfaceAddress != null && interfaceAddress.getAddress().equals(inetAddress)) {
                    short prefix = interfaceAddress.getNetworkPrefixLength();
                    if(prefix > 0 && prefix < 32) return prefix; // some network cards return -1
                    return null;
                }
            }
        }
    }
    return null;
}
 
開發者ID:offbye,項目名稱:DroidDLNA,代碼行數:15,代碼來源:NetworkAddressFactoryImpl.java

示例12: getMaskAddress

import java.net.InterfaceAddress; //導入方法依賴的package包/類
/**
 * 獲得子網掩碼
 * @return
 */
public String getMaskAddress(){
	InterfaceAddress addr=net.getInterfaceAddresses().get(0);
	int add=addr.getNetworkPrefixLength();
	String[] s=new String[]{"0","128","192","224","240","248","252","254","255"};
	if(add>24){
		return "255.255.255."+s[add-24];
	}else if(add>16){
		return "255.255."+s[add-16]+".0";
	}else if(add>8){
		return "255."+s[add-8]+".0.0";
	}else{
		return s[add]+".0.0.0";
	}
}
 
開發者ID:GeeQuery,項目名稱:ef-orm,代碼行數:19,代碼來源:ProcessUtil.java

示例13: scan

import java.net.InterfaceAddress; //導入方法依賴的package包/類
private void scan() {
    logger.debug("Starting scan for Z-Way Server");

    ValidateIPV4 validator = new ValidateIPV4();

    try {
        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());
    }
}
 
開發者ID:openhab,項目名稱:openhab2-addons,代碼行數:36,代碼來源:ZWayBridgeDiscoveryService.java

示例14: getCidrFromInterface

import java.net.InterfaceAddress; //導入方法依賴的package包/類
/**
    * Return the network prefix length. Return 0 if no CIDR detected. FIXME:
    * This method may return -1, which means it may not be the right approach
    */
   public static int getCidrFromInterface(NetworkInterface networkInterface)
    throws IOException {
for (InterfaceAddress address : networkInterface
	.getInterfaceAddresses()) {
    InetAddress inetAddress = address.getAddress();
    if (!inetAddress.isLoopbackAddress()) {
	if (inetAddress instanceof Inet4Address) {
	    return address.getNetworkPrefixLength();
	}
    }
}
return 0;
   }
 
開發者ID:evercam,項目名稱:evercam-discovery-java,代碼行數:18,代碼來源:NetworkInfo.java

示例15: getLocalIpAddressFor

import java.net.InterfaceAddress; //導入方法依賴的package包/類
/**
 * Select the local IP address for connecting the given remote IP address.
 *
 * @param remoteIP - the IP address of the remote host.
 */
static InetAddress getLocalIpAddressFor(InetAddress remoteIP)
{
   Validate.notNull(remoteIP, "no remote IP address given");

   try
   {
      final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
      while (en.hasMoreElements())
      {
         final NetworkInterface iface = en.nextElement();

         for (final InterfaceAddress ifaceAddr: iface.getInterfaceAddresses())
         {
            final int maskLength = ifaceAddr.getNetworkPrefixLength();

            final byte[] remoteRaw = getNetworkAddressOf(remoteIP, maskLength);
            final byte[] localRaw = getNetworkAddressOf(ifaceAddr.getAddress(), maskLength);

            if (Arrays.equals(remoteRaw, localRaw))
               return ifaceAddr.getAddress();
         }
      }

      LOGGER.warn("Did not find a matching network interface, using default local IP");
   }
   catch (SocketException e)
   {
      LOGGER.error("failed to get list of network interfaces, using default local IP", e);
   }

   try
   {
      return InetAddress.getLocalHost();
   }
   catch (UnknownHostException e1)
   {
      throw new RuntimeException("failed to get IP address of local host", e1);
   }
}
 
開發者ID:selfbus,項目名稱:tools-libraries,代碼行數:45,代碼來源:KNXnetLink.java


注:本文中的java.net.InterfaceAddress.getNetworkPrefixLength方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。