티스토리 뷰

 

InetAddress Class: 

인터넷 주소(IP)에 관한 정보를 다루는 클래스, 생성자가 따로 없으며 InetAddress클래스의 정적 메소드에서 정보를 받아오는 형식으로 사용한다.

특이하게도 기본 생성자의 접근 제한자 default이기 때문에 new 연산자 객체를 생성할 수 없다. 따라서 InetAddress 클래스는 객체를 생성해 줄 수 있는 5개의 static 메서드를 제공하고 있다.

 


InetAddress 클래스의 주요 메서드: 

byte[]

getAddress()

IP주소를 byte배열로 반환

static InetAddress[]

getAllByName(String host)

도메인명(host)에 지정된 모든 호스트의 IP주소를 배열로 반환

static InetAddress

getByAddress(byte[] addr)

byte 배열을 통해 IP주소를 얻음

static InetAddress

getByName(String host)

도메인명(host)을 통해 IP주소 얻음

String

getHostAddress()

호스트의 IP주소를 반환

String

getHostName()

호스트의 이름을 반환

static InetAddress

getLocalHost()

지역호스트의 IP주소 반환

boolean

isMulticatAddress()

멀티캐스트 주소인지 확인

boolean

isLoopbackAddress()

loopback 주소인지 확인

 


간단한 예제 코드를 짜보면,

package com.choonham;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class AddressTest {

	public static void main(String args[]) {
		try {
			InetAddress address = InetAddress.getLocalHost();    //사용자의 PC의 정보를 얻음
			System.out.println("로컬 컴퓨터 이름: " + address.getHostName());
			System.out.println("로컬 컴퓨터 IP 주소: " + address.getHostAddress());
			
			address = InetAddress.getByName("til-choonham.tistory.com");
			System.out.println(address);
			
			InetAddress[] all = InetAddress.getAllByName("daum.net");
			
			for(int i = 0; i < all.length; i++) {
				System.out.println(all[i]);
			}
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}  
	}

}

위와 같이 호스트 PC 의 정보, 도메인에 따른 IP주소를 얻어볼 수 있다.

Comments