Chinaunix首页 | 论坛 | 博客
  • 博客访问: 494292
  • 博文数量: 135
  • 博客积分: 3010
  • 博客等级: 中校
  • 技术积分: 905
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-24 19:31
文章分类

全部博文(135)

文章存档

2010年(135)

我的朋友

分类: LINUX

2010-04-13 09:40:33

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("", 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.

阅读(1767) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~