1

您如何以编程方式查找网络掩码支持的主机数量。

例如,如果你有一个 /30 ,你如何在不使用查找表的情况下找到其中有多少 IP?

最好能够使用“/”符号,而不是 255.xxx.xxx.xxx 符号。

4

6 回答 6

4

这是公式: 2 ^ (32 - netmask) - 2 其中 netmask 是一个位数,如您在上面的 Cisco 表示法中所示。因此,带有 /30 掩码的网络有 2 个可用地址。

最低的网络号始终代表网段本身,最高的始终是广播……这导致公式末尾的-2。

对于标准符号,将 aaa.bbb.ccc.ddd 网络掩码转换为无符号 4 字节整数(许多网络库都有此功能)并从 2 ^ 32 - 2 中减去。

于 2008-09-19T02:18:07.263 回答
2

其中 n 是 '/' 后面的数字

>>> def number_of_hosts(n):
...     return 2 ** (32 - n)
... 
>>> number_of_hosts(32)
1
>>> number_of_hosts(30)
4
于 2008-09-19T02:18:25.373 回答
2

方法一:

 package com.test;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class EasyNet {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        try {
              InetAddress localhost = InetAddress.getLocalHost();
              System.out.println(" IP Addr: " + localhost.getHostAddress());
              // Just in case this host has multiple IP addresses....
              InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
              if (allMyIps != null && allMyIps.length > 1) {
                System.out.println(" Full list of IP addresses:");
                for (int i = 0; i < allMyIps.length; i++) {
                  System.out.println("    " + allMyIps[i]);
                }
              }
            } catch (UnknownHostException e) {
              System.out.println(" (error retrieving server host name)");
            }

            try {
              System.out.println("Full list of Network Interfaces:");
              for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                System.out.println("    " + intf.getName() + " " + intf.getDisplayName());
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) 
                {
                  System.out.println("        " + enumIpAddr.nextElement().toString());
                }
              }
            } catch (SocketException e) {
              System.out.println(" (error retrieving network interface list)");
            }
    }

}

方法二:

package com.test;

import java.net.*;
import java.util.*;

public class GetIp {

  public static void main(String args[]) throws Exception {

  Enumeration<NetworkInterface> nets = 
  NetworkInterface.getNetworkInterfaces();

  for (NetworkInterface netint : Collections.list(nets)) {
  System.out.println("\nDisplay name : " + netint.getDisplayName());

  Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();

  for (InetAddress inetAddress : Collections.list(inetAddresses)) {

  System.out.println("InetAddress : " + inetAddress);
  }
  }
  }
}

方法三

package com.test;

import java.io.IOException;
import java.net.InetAddress;

public class Nethosts {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try{
        InetAddress localhost = InetAddress.getLocalHost();
        // this code assumes IPv4 is used
        byte[] ip = localhost.getAddress();
        checkHosts(ip.toString());
        }
        catch(Exception e){
            e.printStackTrace();
        }


    }
    public static void checkHosts(String subnet){
           int timeout=1000;
           for (int i=1;i<254;i++){
               try{
               String host=subnet + "." + i;
               if (InetAddress.getByName(host).isReachable(timeout)){
                   System.out.println(host + " is reachable");
               }
               }
               catch(IOException e){e.printStackTrace();}
           }
        }
}

方法四:

package com.test;

import java.awt.List;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;

public class Netintr {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try
          {
             System.out.println("Output of Network Interrogation:");
             System.out.println("********************************\n");

             InetAddress theLocalhost = InetAddress.getLocalHost();
             System.out.println(" LOCALHOST INFO");
             if(theLocalhost != null)
             {
                System.out.println("          host: " + theLocalhost.getHostName());
                System.out.println("         class: " + theLocalhost.getClass().getSimpleName());
                System.out.println("            ip: " + theLocalhost.getHostAddress());
                System.out.println("         chost: " + theLocalhost.getCanonicalHostName());
                System.out.println("      byteaddr: " + toMACAddrString(theLocalhost.getAddress()));
                System.out.println("    sitelocal?: " + theLocalhost.isSiteLocalAddress());
                System.out.println("");
             }
             else
             {
                System.out.println(" localhost was null");
             }

             Enumeration<NetworkInterface> theIntfList = NetworkInterface.getNetworkInterfaces();
             ArrayList<InterfaceAddress> theAddrList = null;
             NetworkInterface theIntf = null;
             InetAddress theAddr = null;

             while(theIntfList.hasMoreElements())
             {
                theIntf = theIntfList.nextElement();

                System.out.println("--------------------");
                System.out.println(" " + theIntf.getDisplayName());
                System.out.println("          name: " + theIntf.getName());
                System.out.println("           mac: " + toMACAddrString(theIntf.getHardwareAddress()));
                System.out.println("           mtu: " + theIntf.getMTU());
                System.out.println("        mcast?: " + theIntf.supportsMulticast());
                System.out.println("     loopback?: " + theIntf.isLoopback());
                System.out.println("          ptp?: " + theIntf.isPointToPoint());
                System.out.println("      virtual?: " + theIntf.isVirtual());
                System.out.println("           up?: " + theIntf.isUp());

                theAddrList = (ArrayList<InterfaceAddress>) theIntf.getInterfaceAddresses();
                System.out.println("     int addrs: " + theAddrList.size() + " total.");
                int addrindex = 0;
                for(InterfaceAddress intAddr : theAddrList)
                {
                   addrindex++;
                   theAddr = intAddr.getAddress();
                   System.out.println("            " + addrindex + ").");
                   System.out.println("            host: " + theAddr.getHostName());
                   System.out.println("           class: " + theAddr.getClass().getSimpleName());
                   System.out.println("              ip: " + theAddr.getHostAddress() + "/" + intAddr.getNetworkPrefixLength());
                   System.out.println("           bcast: " + intAddr.getBroadcast().getHostAddress());
                   int maskInt = Integer.MIN_VALUE >> (intAddr.getNetworkPrefixLength()-1);
                   System.out.println("            mask: " + toIPAddrString(maskInt));
                   System.out.println("           chost: " + theAddr.getCanonicalHostName());
                   System.out.println("        byteaddr: " + toMACAddrString(theAddr.getAddress()));
                   System.out.println("      sitelocal?: " + theAddr.isSiteLocalAddress());
                   System.out.println("");
                }
             }
          }
          catch (SocketException e)
          {
             e.printStackTrace();
          }
          catch (UnknownHostException e)
          {
             e.printStackTrace();
          }

    }


    public static String toMACAddrString(byte[] a) { if (a == null) { return "null"; } int iMax = a.length - 1;

      if (iMax == -1)
      {
         return "[]";
      }

      StringBuilder b = new StringBuilder();
      b.append('[');
      for (int i = 0;; i++)
      {
         b.append(String.format("%1$02x", a[i]));

         if (i == iMax)
         {
            return b.append(']').toString();
         }
         b.append(":");
      }
    }

    public static String toIPAddrString(int ipa)
    {
       StringBuilder b = new StringBuilder();
       b.append(Integer.toString(0x000000ff & (ipa >> 24)));
       b.append(".");
       b.append(Integer.toString(0x000000ff & (ipa >> 16)));
       b.append(".");
       b.append(Integer.toString(0x000000ff & (ipa >> 8)));
       b.append(".");
       b.append(Integer.toString(0x000000ff & (ipa)));
       return b.toString();
    }

}

方法五

package com.test;

import java.io.IOException;
import java.net.InetAddress;

public class NetworkPing {

    /**
     * JavaProgrammingForums.com
     */
    public static void main(String[] args) throws IOException {

        InetAddress localhost = InetAddress.getLocalHost();
        // this code assumes IPv4 is used
        byte[] ip = localhost.getAddress();

        for (int i = 1; i <= 254; i++)
        {
            ip[3] = (byte)i;
            InetAddress address = InetAddress.getByAddress(ip);
        if (address.isReachable(1000))
        {
            System.out.println(address + " machine is turned on and can be pinged");
        }
        else if (!address.getHostAddress().equals(address.getHostName()))
        {
            //hostName is the Machine name and hostaddress is the ip addr
            System.out.println(address + " machine is known in a DNS lookup");
        }
        else
        {
            System.out.println(address + " the host address and host name are equal, meaning the host name could not be resolved");
        }
        }

    }
}

方法6

package com.test;

import java.net.*;
import java.util.*;

public class NIC {

public static void main(String args[]) throws Exception {

    List<InetAddress> addrList = new ArrayList<InetAddress>();
    Enumeration<NetworkInterface> interfaces = null;
    try {
        interfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        e.printStackTrace();
    }

    InetAddress localhost = null;

    try {
        localhost = InetAddress.getByName("127.0.0.1");
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    while (interfaces.hasMoreElements()) {
        NetworkInterface ifc = interfaces.nextElement();
        Enumeration<InetAddress> addressesOfAnInterface = ifc.getInetAddresses();

        while (addressesOfAnInterface.hasMoreElements()) {
            InetAddress address = addressesOfAnInterface.nextElement();

            if (!address.equals(localhost) && !address.toString().contains(":")) {
                addrList.add(address);
                System.out.println("FOUND ADDRESS ON NIC: " + address.getHostAddress());
            }
        }
    }

}
}
于 2012-02-22T12:41:33.500 回答
0

http://www.unixwiz.net/techtips/netmask-ref.html

这将为您提供确定您需要做什么所需的所有逻辑。

于 2008-09-19T02:16:23.163 回答
0

2^(32-n) - 2,其中 n 是您的数字,在本例中为 30。数字 n 为您提供了地址范围内涵盖的位数,这为您提供了 32-n 位网络。因此,总共有 2^(32-n) 个可能的地址。您为网络和广播地址减去 2 以获得答案。

于 2008-09-19T02:19:26.167 回答
0

使用 /30,您可能只有 4 个主机。

32-30 = 2

2^2 = 4

使用 /24,您可能有 256 个主机 32-24 = 8

8^2 = 256

使用 /23,您可能有 512 个主机 32-23 = 9

9^2 = 512

这是因为子网掩码的位表示

255.255.255.252 转换为

11111111.11111111.11111111.11111100

请注意,最后 2 个字节 = 0。这与 32 - 30 = 2 中的 2 相同

此外,您在每个子网中丢失 2 个 ip,一个用于广播地址,一个用于网关地址

于 2008-09-19T02:26:46.307 回答