Java 길찾기/Java의 정석

[Java] IP주소(IP Address), InetAddress

Kindbeeeear_ 2022. 8. 4. 18:13

IP주소는 컴퓨터(호스트, host)를 구별하는데 사용되는 고유한 값으로 인터넷에 연결된 모든 컴퓨터는 IP주소를 갖는다. IP주소는 4 byte(32 bit)의 정수로 구성되어 있으며, 4개의 정수가 마침표를 구분자로 'a.b.c.d'와 같은 형식으로 표현된다. 여기서 a, b, c, d는 부호없는 1 byte값, 즉 0 ~ 255 사이의 정수이다.

 

IP주소는 다시 네트워크주소와 호스트주소로 나눌 수 있는데, 32 bit(4 byte)의 IP주소중에서 네트워크주소와 호스트주소가 각각 몇 bit를 차지하는지는 네트워크를 어떻게 구성하였는지에 따라 달라진다. 그리고 서로 다른 두 호스트의 IP주소의 네트워크주소가 같다는 것은 두 호스트가 같은 네크워크에 포함되어 있다는 것을 의미한다.

 

윈도우 OS에서 호스트의 IP주소를 확인하려면 콘솔에서 ipconfig.exe를 실행시키면 된다.

 

C:\Documentsna Settings\Administrator>ipconfig
Windows IP Configuration
Ethernet adapter 로컬 영역 연결:
        Connection-specific DNS Suffix
        IP Address. . . . . . . . . . . . : 192. 168. 10. 100
        Subnet Mask. . . . . . . . . . : 255. 255. 255. 0
        Default Gateway . . . . . . . : 192.168.10.1
C:\Documentsna Settings\Administrator>

 

위의 결과에서 얻은 IP주소와 서브넷 마스크를 2진수로 표현하면 다음과 같다.

 

 

IP주소와 서브넷 마스크를 비트연산자 '&'로 연산하면 IP주소에서 네트워크 주소만을 뽑아낼 수 있다.

 

 

'&' 연산자는 bit의 값이 모드 1일 때만 1을 결과로 얻기 때문에 IP주소의 마지막 8bit는 모두 0이 되었다. 이 결과로부터 IP주소 192.168.10.100 의 네트워크 주소는 24bit(192.168.10) 이라는 것과 호스트 주소는 마지막  8 bit(100) 이라는 것을 알 수 있다.

 

IP주소에서 네트워크주소가 차지하는 자리수가 많을수록 호스트 주소의 범위가 줄어들기 때문에 네트워크의 규모가 작아진다. 이 경우 호스트 주소의 자리수가 8자리이기 대문에 256개(2^8)의 호스트만 이 네트워크에 포함될 수 있다.

 

InetAddress

자바에서는 IP주소를 다루기 위한 클래스로 InetAddress를 제공하며 다음과 같은 메서드가 정의되어 있다.

 

메서드 설명
byte[] getAddress IP주소를 byte배열로 반환한다.
static InetAddress[] getAllByName(String host) 도메인명(host)에 지정된 모든 호스트의 IP주소를 배열에 담아 반환한다.
static InetAdderss getByAddress(byte[] addr) byte배열을 통해 IP주소를 얻는다.
static InetAddress getByName(String host) 도메인명(host)을 통해 IP주소를 얻는다.
String getCanonicalHostName() FQDN(fully qualified domain name)을 반환한다.
String getHostAddress() 호스트의 IP 주소를 반환한다.
String getHostName() 호스트의 이름을 반환한다.
static InetAddress getLocalHost() 지역호스트의 IP 주소를 반환한다.
boolean isMulticastAddress() IP주소가 멀티캐스트 주소인지 알려준다.
boolean isLoopbackAddress() IP주소가 loopback 주소(127.0.0.1)인지 알려준다.

 

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

class NetworkEx1 {
    public static void main(String[] args) {
        InetAddress ip = null;
        InetAddress[] ipArr = null;
        
        try {
            ip = InetAddress.getByName("www.naver.com");
            System.out.println("getHostName() : " + ip.getHostName());
            System.out.println("getHostAddress() : " + ip.getHostAddress());
            System.out.println("toString() : " + ip.toString());
            
            byte[] ipAddr = ip.getAddress();
            System.out.println("getAddress() : " + Arrays.toString(ipAddr));
            
            String result = "";
            for(int i=0; i<ipAddr.length; i++) {
                result += (ipAddr[i] < 0) ? ipAddr[i] + 256 : ipAddr[i];
                result += ".";
            }
            System.out.println("getAddress() + 256 : " + result);
            System.out.println();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        
        try {
            ip = InetAddress.getLocalHost();
            System.out.println("getHostName() : " + ip.getHostName());
            System.out.println("getHostAddress() : " + ip.getHostAddress());
            System.out.println();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        
        try {
            ip = InetAddress.getAllByName("www.naver.com");
            
            for(int i=0; i<ipArr.length; i++) {
                System.out.println("ipArr[" + i + "]" + iparr[i]);
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

 

InetAddress의 주요 메서드들을 활용하는 에제이다. 하나의 도메인명(www.naver.com)에 여러 IP주소가 매핑될 수도 있고 또 그 반대의 경우도 가능하기 때문에 전자의 경우 getAllByName()을 통해 모든 IP주소를 얻을 수 있다.

그리고 getLocalHost()를 사용하면 호스트명과 IP주소를 알아낼 수 있다.