Skip to content

Android:Wifi

안드로이드 디바이스의 IP 구하기

진저브레드로 업그레이드 한 후 가끔 3G 와 WiFi 가 둘 다 연결된 것으로 보이는 경우가 있다. 기존에 사용하던 IP 구하는 코드는, 이런 상황에서 3G IP 를 리턴해 준다. 그럼 대략 난감;; 기존 코드는 아래와 같다.

public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException e) {
        Log.e(DEBUG_TAG, "getLocalIpAddress Exception:"+e.toString());
    }
    return null;
}

그래서 WiFi IP 가 있으면 그걸 사용할 수 있게 조금 수정함. 수정된 코드는 아래와 같다.

public String getLocalIpAddress() {
    final String IP_NONE = "N/A";
    final String WIFI_DEVICE_PREFIX = "eth";

    String LocalIP = IP_NONE;
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();           
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    if( LocalIP.equals(IP_NONE) )
                        LocalIP = inetAddress.getHostAddress().toString();
                    else if( intf.getName().startsWith(WIFI_DEVICE_PREFIX) )
                        LocalIP = inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException e) {
        Log.e(DEBUG_TAG, "getLocalIpAddress Exception:"+e.toString());
    }
    return LocalIP;
}

확인 결과 WiFi 장치에 대해 getName() 을 해 보니 "eth0" 을 얻을 수 있었음. 그러므로 "eth" 로 시작하는 장치가 있는 경우 해당 IP 를 LocalIP 라고 판단함.

See also