文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>android get the local ip

android get the local ip

时间:2010-04-13  来源:nearfuture_qinyaomin

The obvious way to get the IP-Address of your device simply doesn’t work on Android.

The first thing I tried was using the WifiInfo.

1
2
3
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();

But wait: ipAddress is an integer? Of course not. I also did the math but couldn’t find a way to get the IP out of this integer. So thats not the right way.

Another possibility I found was to create a socket connection and use the Socket instance to get the local ip address.

1
2
3
4
5
6
try {
    Socket socket = new Socket("www.droidnova.com", 80);
    Log.i("", socket.getLocalAddress().toString());
} catch (Exception e) {
    Log.i("", e.getMessage());
}

The disadvantages should be clear:

  • You generate traffic – may result in costs for the user
  • Your program depend on the Server you create a socket connection to
  • The same exceptions may be thrown for different reasons – bad if you want to display a message to tell the user what he should do to fix the problem

The right thing is to iterate over all network interfaces and iterate there over all ip addresses.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

So if this method returns null, there is no connection available.
If the method returns a string, this string contains the ip address currently used by the device independent of 3G or WiFi.

相关阅读 更多 +
排行榜 更多 +
百炼英雄抽卡技巧指南

百炼英雄抽卡技巧指南

休闲益智 下载
英雄没有闪滚雷旋风技能如何搭配

英雄没有闪滚雷旋风技能如何搭配

休闲益智 下载
英雄没有闪雷旋风BD构筑推荐

英雄没有闪雷旋风BD构筑推荐

休闲益智 下载