www.google.com 의 IP 주소를 구하는 프로그램이다.
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddress_01 {
public static void main(String[] ar) throws Exception {
String[] StrArr = GetIPAddressByName();
for (int i = 0; i < StrArr.length; i++)
System.out.println("IP address : " + StrArr[i]);
}
public static String[] GetIPAddressByName() {
InetAddress[] ia = null;
String[] returnStr = null;
try {
ia = Inet4Address.getAllByName("www.google.com");
} catch (UnknownHostException e) {
e.printStackTrace();
}
returnStr = new String[ia.length];
for (int i = 0; i < ia.length; i++)
returnStr[i] = ia[i].getHostAddress();
return returnStr;
}
}
IPv4 형식의 IP 주소를 가져오게 된다. IPv6 형식의 주소를 가져오는 클래스로 Inet6Address 도 있다.
ia = Inet4Address.getAllByName("www.google.com");
위의 코드에서 getAllByName 은 해당 Name의 도메인 주소에서 모든 IP 주소를 가져오는 것이다.
한 도메인이 한개의 IP 주소를 가지고 있으면 문제가 되지 않지만, 구글과 같은 사이트들은 여려개의 서버를 이용하여 서비스를 하므로 여러 IP 주소가 존재 할 수 있기 때문에 위의 식을 쓴다.
한개의 IP 주소를 가져오려면 getByName 함수를 사용하면된다.
getAllByName 함수는 InetAddress[] 의 형식으로 값을 return 하고
getByName 함수는 InetAddress 의 형식으로 값을 return 한다.
