Programming/Java

java로 Broadcast 계산

keiruX 2008. 4. 10. 13:05

* 네트워크 ID Broadcast 주소 계산 프로그램

  •   컴퓨터의 IP 주소와 서브넷 마스크가 아래와 같이 주어진다.
  • Hint

    •  IP주소와 서브넷 마스크의 각 값은 Keyboard로 입력 받는다.

      • 네트워크 ID

        • IP주소와 서브넷 마스크의 비트연산 AND로 구한다.

        • Broadcast 주소

          • 서브넷 마스크에 보수를 취한 후에 이를 IP 주소와 비트연산 OR로 구한다.
  1. import java.io.*;
    public class Main {
        public static void main(String[] args) throws IOException{
            
     BufferedReader in
      = new BufferedReader(new InputStreamReader(System.in));
     
     String ip=""; /*ip 를 한줄로 입력 받아 저장할 곳*/
     String sub="";
     String []ip2 = new String[4]; /* '.'으로 잘라서 저장할 곳*/
     String []sub2 = new String[4];
     
     int []ip3 = new int[4];/* int 로 변환해서 저장할 곳*/
     int []sub3 = new int[4];
     int []netid = new int[4];
     int []br = new int[4];
     int iFor;

  2.  System.out.println("Input Ip: "); /*ip값 입력*/
     ip = in.readLine();
     
     System.out.println("Input Subnet: ");/*subnet 입력 */
     sub = in.readLine();
  3.  for(iFor=0;iFor<=3;iFor++){
      ip2=ip.split("[.]"); /* '.'을 기준으로 나눔*/
      ip3[iFor]=Integer.parseInt(ip2[iFor]);/* string 를 int형으로 변환 */
  4.   sub2=sub.split("[.]");
      sub3[iFor]=Integer.parseInt(sub2[iFor]);          
     
      netid[iFor] = ip3[iFor]&sub3[iFor]; /*netid*/
      br[iFor] = ip3[iFor]|(byte)~sub3[iFor]; /*브로드 캐스트 보수를 취한뒤 byte 형으로 변환(최고 값 때문에)*/
     } 
     System.out.println("Network ID= "+netid[0]+"."+netid[1]+"."+netid[2]+"."+netid[3]);
     System.out.println("BroadCast = "+br[0]+"."+br[1]+"."+br[2]+"."+br[3]);
        }
    }

이 글은 스프링노트에서 작성되었습니다.