0

我在 android manifest 文件中授予访问 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 地址用于聊天应用程序。

4

2 回答 2

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;
}
于 2012-08-02T13:01:45.797 回答
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;
}
于 2012-08-02T13:00:19.650 回答