문제

넷마스크가 지원하는 호스트 수를 프로그래밍 방식으로 어떻게 찾나요?

예를 들어 /30 이 있는 경우 조회 테이블을 사용하지 않고 IP가 몇 개 있는지 어떻게 알 수 있나요?

255.xxx.xxx.xxx 표기법보다는 "/" 표기법을 사용하는 것이 좋습니다.

도움이 되었습니까?

해결책

공식은 다음과 같습니다.2 ^ (32 - 넷마스크) - 2 여기서 넷마스크는 위의 Cisco 표기법에 표시된 대로 비트 수입니다.따라서 /30 마스크가 있는 네트워크에는 사용 가능한 주소가 2개 있습니다.

가장 낮은 네트워크 번호는 항상 네트워크 세그먼트 자체를 나타내고 가장 높은 네트워크 번호는 항상 브로드캐스트입니다.이로 인해 수식 끝에 -2가 표시됩니다.

표준 표기법의 경우 aaa.bbb.ccc.ddd 넷마스크를 부호 없는 4바이트 정수(많은 네트워킹 라이브러리에 이 기능이 있음)로 변환하고 이를 2 ^ 32 - 2에서 뺍니다.

다른 팁

여기서 n은 '/' 다음의 숫자입니다.

>>> def number_of_hosts(n):
...     return 2 ** (32 - n)
... 
>>> number_of_hosts(32)
1
>>> number_of_hosts(30)
4

방법 1:

 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)");
            }
    }

}

방법 2:

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);
  }
  }
  }
}

방법 3

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();}
           }
        }
}

방법 4:

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();
    }

}

방법 5

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());
            }
        }
    }

}
}

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

이는 수행해야 할 작업을 결정하는 데 필요한 모든 논리를 제공합니다.

2^(32-n) - 2, 여기서 n은 숫자이며, 이 경우에는 30입니다.숫자 n은 주소 범위에 포함되는 비트 수를 제공하며, 이는 네트워크에 남은 32-n 비트를 제공합니다.따라서 총 2^(32-n)개의 주소가 가능합니다.답을 얻으려면 네트워크 및 브로드캐스트 주소에 대해 2를 뺍니다.

/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개의 IP를 잃습니다. 하나는 브로드캐스트 주소용이고 다른 하나는 게이트웨이 주소용입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top