Java & Android
Android 4.0 get local IP Address
우동우동우
2012. 4. 10. 22:45
과거에 인터넷에서 로컬 IP 주소를 받아오는 메서드를 인터넷에서 검색하여 한동안 잘 사용하고 있었다.
그런데 4.0에서 갑자기... 안되는.. 황당한 시츄에이션...
다시 잘 살펴보니 IPv6 형태의 주소를 가져 오고 있었다.
그래서 아래와 같이 메서드에 약간의 수정을 하여서 IPv4 형태의 IP 주소를 가져오게 하였다.
public final static int TYPE_INET4ADDRESS = 1; public final static int TYPE_INET6ADDRESS = 2; public static String getLocalIpAddress(int type) { try { for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = ( NetworkInterface ) en.nextElement(); for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = ( InetAddress ) enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { switch (type) { case TYPE_INET6ADDRESS: if (inetAddress instanceof Inet6Address) { return inetAddress.getHostAddress().toString(); } break; case TYPE_INET4ADDRESS: if (inetAddress instanceof Inet4Address) { return inetAddress.getHostAddress().toString(); } break; } } } } }catch (Exception e) { } return null; }