public String getLocalIpAddress(){
final String IP_NONE = "N/A";
final String WIFI_DEVICE_PREFIX = "eth";
String LocalIP = IP_NONE;
try {
NetworkInterface.getNetworkInterfaces();
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration 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("MainActivity.class", "getLocalIpAddress Exception:"+e.toString());
}
return LocalIP;
}
public String getLocalIpAddress(){
final String IP_NONE = "N/A";
final String WIFI_DEVICE_PREFIX = "eth";
String LocalIP = IP_NONE;
try {
NetworkInterface.getNetworkInterfaces();
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration 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("MainActivity.class", "getLocalIpAddress Exception:"+e.toString());
}
return LocalIP;
}
public String getLocalIpAddress(){ final String IP_NONE = "N/A"; final String WIFI_DEVICE_PREFIX = "eth"; String LocalIP = IP_NONE; try { NetworkInterface.getNetworkInterfaces(); for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration 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("MainActivity.class", "getLocalIpAddress Exception:"+e.toString()); } return LocalIP; }
출처: http://blog.naver.com/ziippy/120138070384
안드로이드에서 ip 구하는코드가 필요해서 검색해서 사용하는데 자꾸 에러가 발생함NetworkInterface.getNetworkInterfaces(); 이부분에서 자꾸 Exception 발생해서 삽질하다가 깨달은것 퍼미션 문제…
그리고 퍼미션도 “android.permission.ACCESS_NETWORK_STATE” 이게 아니라 <uses-permission android:name=”android.permission.INTERNET”/> 이거였음
답글 남기기