Android App2014.05.09 10:36

 

public String getLocalIpAddress() {
        try {
                Enumeration<NetworkInterface> en =  NetworkInterface.getNetworkInterfaces();               
                while(en.hasMoreElements()) {
                       NetworkInterface interf = en.nextElement();                      
                       Enumeration<InetAddress> ips = interf.getInetAddresses();
                            while (ips.hasMoreElements()) {
                              InetAddress inetAddress = ips.nextElement();
                              if (!inetAddress.isLoopbackAddress()) {
                                      return inetAddress.getHostAddress().toString();
                           }
                    }
                }
        } catch (SocketException ex) {
                //Log.e("Error", ex.toString());
         System.out.println(ex.toString());
         
        }
            return null;
      }

 

여러가지 소스를 찾아봤지만 이게 가장 깔끔한거 같다...

 

만약 그냥 저소스를 그대로 쓰면 에러가 난다.

 

NetworkInterface.getNetworkInterfaces();               

 

이부분 에서 exception이 나는데 권한이 없다고 나와서 보니

 

manifest에

 

   <uses-permission android:name="android.permission.INTERNET"/>

 

를 추가하니 잘되었다.

Posted by 동동(이재동)