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
(자바) 클라이언트 소켓 프로그래밍 (Client Socket Programming) (0) | 2019.01.31 |
---|---|
(자바) SocketAddress 클래스 & NetworkInterface 클래스 (0) | 2019.01.31 |
(자바) 람다 표현식 기본적 표현(JAVA8 Lambda expression) (0) | 2019.01.06 |
(자바) Arrays.sort와 Arrays.parallelSort 성능비교 (Arrays) (0) | 2019.01.05 |
자바 가상 기계(JVM : Java Virtual Machine) (0) | 2018.12.25 |