Enjoy Development

지식관리, 메모장, 기억저장소, 참고자료, ...

Java ShowIP Class

2014.02.10 15:17 | 조회 수 : 26186

Java에서 IP주소를 가져오는 소스.

 

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class ShowIP {
    public static void main(String[] args){
        String ip = null;

        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();

            while (en.hasMoreElements()) {
                NetworkInterface intf = en.nextElement();

                if (intf.isUp() && !intf.isLoopback()) {
                    // 작동중이고(isUp) 루프백(isLoopback)이 아닌 경우...
                    System.out.println("=======================================================================");
                    System.out.println("Interface Name : " + intf.getDisplayName());
                    System.out.println(" - Is Loopback : " + intf.isLoopback());
                    System.out.println(" - Is Virtual : " + intf.isVirtual());
                    System.out.println(" - Is Up : " + intf.isUp());

                    Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();

                    while (enumIpAddr.hasMoreElements()) {
                        InetAddress inetAddress = enumIpAddr.nextElement();

                        if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                            // 루프백(isLoopback)이 아니고 링크 로컬 주소(isLinkLocalAddress)가 아닌 경우...
                            byte[] ipAddr = inetAddress.getAddress();
                            ip = (ipAddr[0] & 0xFF) + "." + (ipAddr[1] & 0xFF) + "." + (ipAddr[2] & 0xFF) + "." + (ipAddr[3] & 0xFF);

                            System.out.println("-----------------------------------------------------------------------");
                            System.out.println("IP : " + ip);
                            System.out.println(" - Is Loopback : " + inetAddress.isLoopbackAddress());
                            System.out.println(" - Is Link Local Address : " + inetAddress.isLinkLocalAddress());
                            System.out.println(" - Is Site Local Address : " + inetAddress.isSiteLocalAddress());
                        }
                    }
                    System.out.println("=======================================================================");
                    System.out.println("");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Powered by EnjoyDev | Xpress Engine | DNS Powered by DNSEver.com