我給出了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地址的聊天應用程序中使用。
這段代碼給我的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