본문 바로가기

자바의 정석 정리

자바의 정석 - 16.2 InetAddress

16.2.1 InetAddress

  • Java에서 IP를 다루기 위한 클래스
byte[] getAddress() //IP주소를 byte배열로 반환한다.
static InetAddress[] getAllByName(String host) //도메인명(host)을 통해 IP주소를 얻는다.
static InetAddess getByAddess(byte[] addr) //byte배열을 통해 IP주소를 얻는다.
static InetAddress getByName(String host) //도메인명(host)에 지정된 모든 호스트의 IP주소를 배열에 담아 반환한다.
static InetAddress getLocalHost() //지역호스트의 IP주소를 반환한다.
String getCanonicalHostName() //Fully Qualified Domain Name을 반환한다.
String getHostAddress() //호스트의 IP주소를 반환한다.
String getHostName() //호스트의 이름을 반환한다.
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 {
            ipArr = 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();
        }

    } // main
}

/*
getHostName() :www.naver.com
getHostAddress() :210.89.164.90
toString() :www.naver.com/210.89.164.90
getAddress() :[-46, 89, -92, 90]
getAddress()+256 :210.89.164.90
getHostName() :MSDN-SPECIAL
getHostAddress() :192.168.17.1
ipArr[0] :www.naver.com/210.89.164.90
ipArr[1] :www.naver.com/125.209.222.141
*/