개인 PC는 드물지만, 서버는 이런 저런 이유로 한개 이상의 IP를 지정해 놓을때가 있다.
IP가 하나일때는, InetAddress클래스의 static메소드를 통해서 쉽게 주소객체를 얻을수있다.
//대표(?) IP하나만 얻어올때
try {
InetAddress add = InetAddress.getLocalHost();
System.out.println(add.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
그렇지만, 저 서버처럼 IP가 여러개인 경우에도 아이픽 목록을 얻으려고
getAllByName("localhost") 로 해보았지만, 대표IP하나만 얻을수 있었고
System.getPopreties로 얻은 프로퍼티에도 역시나 나오지 않았다.
java.net패키지에서 NetworkInterface 를 찾고 답을 얻었다.
static Enumeration |
getNetworkInterfaces() Returns all the interfaces on this machine. |
대충 코드는..
결과는, 다음과 같다.
예약된 IP인 127.0.0.1과 NIC에 물린(IP의 목록을 구할수 있음).
name:lo (MS TCP Loopback interface) index: 1 addresses: <- NetworkInerface의 toString() 값
/127.0.0.1; <- InerAddress의 IP값
name:eth0 (Realtek RTL8168/8111 PCI-E Gigabit Ethernet NIC - ÆÐ? ½º????? ¹?? Æ÷?) index: 2 addresses: <- NetworkInerface의 toString() 값
/210.XXX.XXX.120; <- InerAddress의 IP값
/210.XXX.XXX.78;
/210.XXX.XXX.118;
/210.XXX.XXX.119;