2012-08-02 99 views
0

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

回答

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; 
} 
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; 
} 
+0

這段代碼給我的IPv6地址,但我想它在IPv4地址。請建議我轉換IPv6到IPv4地址的java代碼。 – 2012-08-05 06:41:47

+0

@jay你有同樣的解決方案,請分享,如果你有。 – pyus13 2013-08-14 08:42:30

+0

InetAddressUtils.isIPv4Address可能有用嗎? – 2013-08-14 12:54:41