Android 如何获取网络/Wi-Fi IP

问题描述 投票:0回答:3

我有一个问题想要获取我的移动IP

是否是网络或Wi-Fi

我尝试了一些方法,但我不知道为什么我无法得到它

 public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getLocalIpAddress();
    }
    public String getLocalIpAddress(){
        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()){
                                    Log.e("IP", inetAddress.getHostAddress().toString());
                                    return inetAddress.getHostAddress().toString();
                                }
                    }
            }
        } catch (SocketException ex) {
            Log.e( "Error:" , ex.toString());
          }
        return null ;
        }
}

这是我的日志

fe80::a3c8:4c03:154:8e1d%rmnet_usb0

这是我的 AndroidManifest

 <uses-permission android:name= "android.permission.INTERNET" />  
    <uses-permission android:name= "android.permission.ACCESS_WIFI_STATE" /> 
    <uses-permission android:name= "android.permission.ACCESS_NETWORK_STATE" />
android android-networking
3个回答
1
投票

请尝试一下,它可能对您有帮助:

public String getLocalIpAddress()
{
    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 (Exception ex) {
        Log.e("IP Address", ex.toString());
    }
    return null;
}

在清单文件中添加以下权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

0
投票

用它来获取设备IP地址:

WifiManager wm = (WifiManager) this.getSystemService(this.WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

0
投票

你可以试试这个:

private String getIPAddress(Context context) {

    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    int ip = wifiInfo.getIpAddress();
    return Formatter.formatIpAddress(ip);
}
© www.soinside.com 2019 - 2024. All rights reserved.