如何获取我的Android设备的动态IP地址
问题描述:
我给出了android清单文件中访问Internet的权限,如下所示。 <uses-permission android:name="android.permission.INTERNET" />
如何获取我的Android设备的动态IP地址
以下代码将写入简单的应用程序。
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地址的聊天应用程序中使用。
答
您可以使用以下代码获取连接到设备的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;
}
答
这段代码会给你的本地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;
}
这段代码给我的IPv6地址,但我想它在IPv4地址。请建议我转换IPv6到IPv4地址的java代码。 – 2012-08-05 06:41:47
@jay你有同样的解决方案,请分享,如果你有。 – pyus13 2013-08-14 08:42:30
InetAddressUtils.isIPv4Address可能有用吗? – 2013-08-14 12:54:41