如何获取我的Android设备的动态IP地址

时间:2012-08-02 12:42:25

标签: android dynamic ip-address

我允许在android清单文件中访问Internet,如下所示。 <uses-permission android:name="android.permission.INTERNET" />

以下代码将以简单的应用程序编写。

package com.GetIP;


import java.net.InetAddress;
import android.app.Activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class IPAddress extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button b=(Button)findViewById(R.id.btn1);

    b.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            // TODO Auto-generated method stub
             try
                {
                    InetAddress ownIP=InetAddress.getLocalHost();
                    //System.out.println("IP of my Android := "+ownIP.getHostAddress());

                    Toast.makeText(getApplicationContext(), ownIP.toString(), Toast.LENGTH_LONG).show();
                }
                catch (Exception e)
                {
                    System.out.println("Exception caught ="+e.getMessage());
                    }
        }
    });
}

}

上面的代码给出了localhost / 127.0.0.1,但是它是一个默认的ip地址,但我希望我的设备的动态ip地址用于聊天应用程序。

2 个答案:

答案 0 :(得分:1)

这段代码将为您提供本地IP地址:

public static String getLocalIpAddressString() {
    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) {
    }

    return null;
}

答案 1 :(得分:0)

您可以使用以下代码获取附加到设备的IP地址列表。

public static List<String> getLocalIpAddress() {
    List<String> list = new ArrayList<String>();
    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()) {
                    list.add(inetAddress.getHostAddress().toString());
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(TAG, ex.toString());
    }
    return list;
}