우동우동우's note

[Android] 4.0 이상에서 IP 주소 가져오기 본문

Java & Android

[Android] 4.0 이상에서 IP 주소 가져오기

우동우동우 2013. 11. 25. 19:55


과거에 인터넷에서 로컬 IP 주소를 받아오는 메서드를 인터넷에서 검색하여 한동안 사용하고 있었다.

그런데 4.0에서 갑자기... 안되는.. 황당한 시츄에이션...


다시 살펴보니 IPv6 형태의 주소를 가져 오고 있었다.


그래서 아래와 같이 메서드에 약간의 수정을 하여서 IPv4 형태의 IP 주소를 가져오게 하였다.

public final static int INET4ADDRESS = 1;
public final static int 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 INET6ADDRESS:
      if (inetAddress instanceof Inet6Address) {
       return inetAddress.getHostAddress().toString();
      }
      break;
     case INET4ADDRESS:
      if (inetAddress instanceof Inet4Address) {
       return inetAddress.getHostAddress().toString();
      }
      break;
     }
     
    }
   }
  }
 } catch (SocketException ex) {
 }
 return null;
}


Comments