Language/Java

[이것이 자바다] IP 주소 얻기

깨구르르 2024. 3. 13. 00:40
728x90

자바는 IP 주소를 java.net 패키지의 InetAddress로 표현한다.

👉 로컬 컴퓨터의 IP 주소를 얻을 수 있다.

👉 도메인 이름으로 DNS에서 검색한 후 IP 주소를 가져올 수도 있다.

 

1. getLocalHost 사용


InetAddress ia = InetAddress.getLocalHost();


👉 .getLocalHost() 메소드를 통해 로컬 컴퓨터의 InetAddress를 얻을 수 있다.

 

getLocalHost를 사용하는 이유❓

InetAddress직접적으로 객체를 생성할 수 없다.

👉 정적 메소드인 getLocalHost를 이용해 간접적으로 객체를 얻을 수 있다.

👉  로컬 pc의 ip 주소를 갖고 있는 inetAddress를 얻을 수 있다.

 

 


 

 

2. getByName, getAllByName 사용

만약 컴퓨터 도메인 이름을 알고 있다면 다음 두 개의 메소드를 사용하여 InetAddress 객체를 얻을 수 있다.


InetAddress ia = InetAddress.getByName(String domainName);

InetAddress[ ] iaArr = InetAddress.getAllByName(String domainName);


👉 도메인 이름을 이용하기 때문에 내부적으로 DNS를 이용한다는 것을 유추할 수 있다.

 

  • getByName() : DNS에서 도메인 이름으로 등록된 단 하나의 IP 주소를 가져옴
  • getAllByName() : DNS에서 도메인 이름으로  등록된 모든 IP 주소배열로 가져옴

 

getAllByName 사용하는 이유❓

서버는 불특정 다수를 위해 서비스를 해야 하기 때문에 하드웨어 성능이 뛰어나야 한다.

문제점은 하드웨어 성능이 한정적이라는 것이다.

따라서 규모가 큰 웹 사이트들은 부하를 균등하게 배분하기 위해 하나의 도메인 이름을 사용하되, 서버를 여러 개를 사용하게 된다.

 

 


 

 

3. getHostAddress() 사용

위 메소드들로 얻은 InetAddres 객체에서 IP 주소를 얻으려면 getHostAddress() 메소드를 다음과 같이 호출하면 된다.


String ip = InetAddress.getHostAddress();


👉 리턴값은 문자열로 된 IP 주소

 


 

4. 예제

package ch19.sec02;

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

public class InetAddressExample [
	public static void main(String[] args) {
    	try {
        	InetAddress local = InetAddress.getLocalHost();
            System.out.println("내 컴퓨터 IP 주소: " + local.getHostAddress());
            
            InetAddress[] iaArr = InetAddress.getAllByName("www.naver.com");
            for(InetAddress remote : iaArr) {
            	System.out.println("www.naver.com IP 주소: " + remote.getHostAddress());
            }
        } catch(UnkonwnHostException e) {
        	e.printStackTrace();
        }
    }
}

 

728x90