본문 바로가기

IT

socket 통신에서 접속한 서버의 Address 알아보기

반응형

 일반적으로 URL을 이용하여 접속을 시도하는데 이럴때 아이피번호를 알고 싶거나, 접속하고 있는 서버의 도메인을 알고 싶은 경우가 있다. 이럴 경우 정보를 얻는 방법은 다음과 같다.

 대중적인(?) 다음넷을 연결해 보자.


package org.dante2k.test.socket;

import java.io.IOException;
import java.net.Socket;

public class SocketTest {
	public static void main(String[] args) {
		Socket socket = null;
		
		try {
			socket = new Socket("www.daum.net", 80); 
			
			System.out.println("InetAddress:" + socket.getInetAddress().toString());
			System.out.println("HostAddress:" + socket.getInetAddress().getHostAddress());
			System.out.println("HostName:" + socket.getInetAddress().getHostName());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (socket != null)
				try { socket.close(); } catch (IOException e) { }
		}
	}
}


결과는 다음과 같다.


// 실제 아이피는 다를 수 있습니다.
InetAddress:www.daum.net/61.111.62.165
HostAddress:61.111.62.165
HostName:www.daum.net

 getInetAddress.toString() 을 이용하여 contains()함수를 이용하여 아이피나 도메인이 자신이 원하는 정보와 같은지 확인할 수 있고, getInetAddress().getHostAddress()는 아이피를, getInetAddress().getHostName()은 도메인 정보를 얻을 수 있다.

반응형