상세 컨텐츠

본문 제목

(자바) InetAddress 클래스

Programming language/자바

by choiDev 2019. 1. 31. 09:38

본문

InetAddress 클래스


통신 프로그램은 사실 인터넷이나 통신 규격이 요구하는 프로토콜을 만족시키는 데이터를 만드는 작업이다.

InetAddress 클래스는 인터넷 도메인이나 호스트를 IP주소로 전환하는 기능을 한다.


InetAddress클래스 특징

   - 객체를 생성하면 수정할 수 없다.

   - InetAddress 클래스는 일반적으로 IPv4 주소를 사용한다.


[IP주소 반환 받는 예제]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class StringExample {
public static void main(String args[]){
InetAddress thisComputer = null;

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter names and IP address. Enter \"exit\" to quit.");
try{
while(true){
String host = in.readLine();

if(host.equalsIgnoreCase("exit") ||
host.equalsIgnoreCase("quit")){
break;
}

try{
thisComputer = InetAddress.getByName(host);

System.out.println(thisComputer.getHostAddress());

if(thisComputer.isReachable(2000)){
System.out.printf("%s is reachable \n",thisComputer.getHostName());
}else{
System.out.printf("%s is unreachable \n",thisComputer.getHostName());
}
}catch(UnknownHostException e){
System.out.println("Connot find host " + host);
}
}
}catch(IOException e){
System.err.println(e);
}
}
}

[결과]

Enter names and IP address. Enter "exit" to quit.
www.google.com
172.217.161.196
www.google.com is unreachable
127.0.0.1
127.0.0.1
localhost is reachable
quit

Process finished with exit code 0


[IP주소를 모두 받아오는 예제]

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

public class StringExample {
public static void main(String args[]){
InetAddress address[] = null;
String temp = "www.naver.com";

try{
address = Inet4Address.getAllByName(temp);
for(InetAddress each: address){
System.out.println("Name : " + each.getHostName());
System.out.println("Addr : " + each.getHostAddress());
System.out.println("Canonical : " + each.getCanonicalHostName());
}

}catch(UnknownHostException e){
System.out.println("Name : " + args[0]);
}
}
}

[결과]

Name : www.naver.com
Addr : 125.209.222.141
Canonical : 125.209.222.141
Name : www.naver.com
Addr : 210.89.164.90
Canonical : 210.89.164.90


관련글 더보기