private static 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()) {
if (inetAddress instanceof Inet4Address) { //ipv4
Inet4Address inet4 = (Inet4Address) inetAddress;
String local_ip = inet4.getHostAddress();
if (inetAddress.isSiteLocalAddress()) { // 내부망일때
return local_ip;
}
}else{ //ipv6
String local_ip = inetAddress.getHostAddress();
Log.d(TAG,"LocalIPv6 Address:"+local_ip);
}
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
또는
WifiManager wm = (WifiManager)getSystemService(WIFI_SERVICE);
WifiInfo wi = wm.getConnectionInfo();
int ipAddr = wi.getIpAddress();
String ip = String.format("%d.%d.%d.%d",
(ipAddr & 0xff),
(ipAddr >> 8 & 0xff),
(ipAddr >> 16 & 0xff),
(ipAddr >> 24 & 0xff));
wifi off 일땐 0 리턴