JAVA/NetWork

InetAddress 클래스

lavender1122 2024. 2. 14. 19:19
  • IP주소 정보 다루기 위한 클래스

InetAddress.getbyName("주소") : 사이트 IP정보 가져오기

  • http://www.naver.com(도메인네임) 또는 SEM-PC 등과 같은 머신이름이나 IP주소를 파라미터로 사용하여 유효한 InetAddress 객체를 생성한다
  •  IP주소 자체를 넣으면 주소 구성 자체의 유효성 정도만 체크가 이루어진다.
InetAddress 변수명 = InetAddress.getByName("사이트주소");
  • 예시
    • 네이버사이트의 IP 정보 가져오기
InetAddress naverIp = InetAddress.getByName("www.naver.com");

InetAddress변수명.getHostName() : 도메인 네임 호출

InetAddress변수명.getHostName()
  • 예시
    • 네이버사이트의 도메인 네임 호출
System.out.println("Host Name => "+naverIp.getHostName());


InetAddress변수명.getHostAddress() : IP주소 호출

InetAddress변수명.getHostAddress()
  • 예시
    • 네이버사이트 IP주소 호출
System.out.println("Host Address =>" + naverIp.getHostAddress());


자신 컴퓨터의 IP정보 가져오기

InetAddress.getLocalHost() : 자신 컴퓨터의 IP 정보 가져오기

InetAddress 변수명 = InetAddress.getLocalHost();

예시

InetAddress localIp = InetAddress.getLocalHost();

System.out.println("내 컴퓨터의 Host Name =>" + localIp.getHostName());


InetAddress.getAllByName("주소") :IP주소가 여러개인 호스트 정보 가져오기

InetAddress[] 변수명 = InetAddress.getAllByName("주소");

 

InetAddress[] naverIps = InetAddress.getAllByName("www.naver.com");
for (InetAddress iAddr : naverIps) {
			System.out.println(iAddr.toString());
		}


원본

더보기
package kr.or.ddit.basic;

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

public class InetAddressTest {
	
	public static void main(String[] args) throws UnknownHostException {
		// InetAddress 클래스 => IP주소 정보를 다루기 위한 클래스
		
		//getByName() 메서드는 www.naver.com(도메인네임) 또는 SEM-PC 등과 같은 머신이름이나
		// IP주소를 파라미터로 사용하여 유효한 InetAddress 객체를 생성한다
		// IP주소 자체를 넣으면 주소 구성 자체의 유효성 정도만 체크가 이루어진다.

		// 네이버 사이트의 IP정보가져오기
		InetAddress naverIp = InetAddress.getByName("www.naver.com");
		//도메인네임
		System.out.println("Host Name => "+naverIp.getHostName());
		//ip 주소
		System.out.println("Host Address =>" + naverIp.getHostAddress());
		System.out.println();
		
		//자기 자신 컴퓨터의 IP정보 가져오기
		InetAddress localIp = InetAddress.getLocalHost();
		System.out.println("내 컴퓨터의 Host Name =>" + localIp.getHostName());
		System.out.println("내 컴퓨터의 Host Address =>" + localIp.getHostAddress());
		System.out.println();
		
		//IP주소가 여러개인 호스트의 정보 가져오기
		InetAddress[] naverIps = InetAddress.getAllByName("www.naver.com");
		
		for (InetAddress iAddr : naverIps) {
			System.out.println(iAddr.toString());
		}
	}
}