0

在我的应用程序中,我需要获取服务器 ip .. 我获取 ip 的代码是

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();
                Log.v("","ip1--:" + inetAddress);
                Log.v("", "ip2--:" + inetAddress.getHostAddress());       
                String ipv4;
      if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())) {

                    String ip = inetAddress.getHostAddress().toString();
                    Toast.makeText(getApplicationContext(), inetAddress., Toast.LENGTH_SHORT).show();
                    Log.v("","ip---::" + ip);
                    // return inetAddress.getHostAddress().toString();
                    return ipv4;
                }
            }
        }

但如果设备连接到联网的 wifi 设备,它会返回本地地址。请告诉我如何获取网络的父 ip。提前致谢...

4

2 回答 2

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

请注意,ipAddress 是一个整数。

例如,如果您的 IP 地址是“86.52.119.245”:

the int returned by getIpAddress will be 4118230102.
Translated into binary this number is: 11110101 01110111 00110100 01010110.
Convert each byte into a decimal, and then you get the numbers: 80 35 83 10
Notice that the numbers are in network order so you have to flip it.
于 2012-09-10T06:42:15.233 回答
1
private String wifi_ip() 
    {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet("http://wiki.iti-lab.org/ip.php");
            HttpResponse response;

            response = httpclient.execute(httpget);

            // Log.i("externalip",response.getStatusLine().toString());

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                long len = entity.getContentLength();
                if (len != -1 && len < 1024) {
                    String str = EntityUtils.toString(entity);
                    // Log.i("externalip",str);
                    // ip.setText(str);
                    ip1 = str;
                }
            }
        } catch (Exception e) {
            // ip.setText("Error");
        }
        return ip1;
    }
于 2012-09-10T12:35:59.780 回答