如何从代码中获取设备的IP地址?

459

有没有可能使用一些代码获取设备的IP地址?


6
请记住,这是一个大小为N的集合,您不能假设N ==(0 || 1)。换句话说,不要假设设备只有一种与网络通信的方式,也不要假定它根本没有与网络通信的方式。 - James Moore
相关:https://dev59.com/IGkx5IYBdhLWcg3wCP-Y - AlikElzin-kilaka
2
如何查看我的Android手机的IP地址? - Ciro Santilli OurBigBook.com
你应该从外部服务获取它,http://ipof.in/txt 就是这样的一个服务。 - vivekv
在Android中,是否可以通过编程方式获取它? - Tanmay Sahoo
请查看我的答案:https://dev59.com/ymQn5IYBdhLWcg3wkH3U#50871614 - Yong
32个回答

1

引用 // 获取设备IP地址

open fun getLocalIpAddress(): String? {
    try {
        val en: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()
        while (en.hasMoreElements()) {
            val networkInterface: NetworkInterface = en.nextElement()
            val enumerationIpAddress: Enumeration<InetAddress> = networkInterface.inetAddresses
            while (enumerationIpAddress.hasMoreElements()) {
                val inetAddress: InetAddress = enumerationIpAddress.nextElement()
                if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                    return inetAddress.getHostAddress()
                }
            }
        }
    } catch (ex: SocketException) {
        ex.printStackTrace()
    }
    return null
}

1

将一些想法编译成更好的Kotlin解决方案,以获取WifiManager的wifi IP:

private fun getWifiIp(context: Context): String? {
  return context.getSystemService<WifiManager>().let {
     when {
      it == null -> "No wifi available"
      !it.isWifiEnabled -> "Wifi is disabled"
      it.connectionInfo == null -> "Wifi not connected"
      else -> {
        val ip = it.connectionInfo.ipAddress
        ((ip and 0xFF).toString() + "." + (ip shr 8 and 0xFF) + "." + (ip shr 16 and 0xFF) + "." + (ip shr 24 and 0xFF))
      }
    }
  }
}

或者您可以通过NetworkInterface获取ip4环回设备的IP地址:

fun getNetworkIp4LoopbackIps(): Map<String, String> = try {
  NetworkInterface.getNetworkInterfaces()
    .asSequence()
    .associate { it.displayName to it.ip4LoopbackIps() }
    .filterValues { it.isNotEmpty() }
} catch (ex: Exception) {
  emptyMap()
}

private fun NetworkInterface.ip4LoopbackIps() =
  inetAddresses.asSequence()
    .filter { !it.isLoopbackAddress && it is Inet4Address }
    .map { it.hostAddress }
    .filter { it.isNotEmpty() }
    .joinToString()

1
这是 Kotlin 版本的 @Nilesh 和 @anargund。
  fun getIpAddress(): String {
    var ip = ""
    try {
        val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
        ip = Formatter.formatIpAddress(wm.connectionInfo.ipAddress)
    } catch (e: java.lang.Exception) {

    }

    if (ip.isEmpty()) {
        try {
            val en = NetworkInterface.getNetworkInterfaces()
            while (en.hasMoreElements()) {
                val networkInterface = en.nextElement()
                val enumIpAddr = networkInterface.inetAddresses
                while (enumIpAddr.hasMoreElements()) {
                    val inetAddress = enumIpAddr.nextElement()
                    if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                        val host = inetAddress.getHostAddress()
                        if (host.isNotEmpty()) {
                            ip =  host
                            break;
                        }
                    }
                }

            }
        } catch (e: java.lang.Exception) {

        }
    }

   if (ip.isEmpty())
      ip = "127.0.0.1"
    return ip
}

5
如果这是你在实际项目中的代码风格,我建议你阅读罗伯特·马丁的《代码整洁之道》。 - Ahmed Adel Ismail

0

你可以做到这个

String stringUrl = "https://ipinfo.io/ip";
//String stringUrl = "http://whatismyip.akamai.com/";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(MainActivity.instance);
//String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, stringUrl,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // Display the first 500 characters of the response string.
                Log.e(MGLogTag, "GET IP : " + response);

            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        IP = "That didn't work!";
    }
});

// Add the request to the RequestQueue.
queue.add(stringRequest);

0
请检查这段代码...使用这段代码,我们将从移动互联网获取IP地址...
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();
                    }
                }
            }

0

针对Kotlin语言。

fun contextIP(context: Context): String {
    val wm: WifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
    return Formatter.formatIpAddress(wm.connectionInfo.ipAddress)
}

弃用的方法 - MisterAnt
不推荐使用的方法 - MisterAnt

0

我不做Android,但我会用完全不同的方式来解决这个问题。

向Google发送一个查询,例如: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=my%20ip

并参考响应发布的HTML字段。您也可以直接查询源代码。

谷歌可能会比您的应用程序存在更长的时间。

请记住,可能您的用户此时没有互联网连接,您希望发生什么!

祝你好运


有趣!我敢打赌Google有某种API调用可以返回您的IP,这将比扫描HTML更稳定。 - SMBiggs

0

如果您有一个 shell;ifconfig eth0 也适用于 x86 设备。


0
 //    @NonNull
    public static String getIPAddress() {
        if (TextUtils.isEmpty(deviceIpAddress))
            new PublicIPAddress().execute();
        return deviceIpAddress;
    }

    public static String deviceIpAddress = "";

    public static class PublicIPAddress extends AsyncTask<String, Void, String> {
        InetAddress localhost = null;

        protected String doInBackground(String... urls) {
            try {
                localhost = InetAddress.getLocalHost();
                URL url_name = new URL("http://bot.whatismyipaddress.com");
                BufferedReader sc = new BufferedReader(new InputStreamReader(url_name.openStream()));
                deviceIpAddress = sc.readLine().trim();
            } catch (Exception e) {
                deviceIpAddress = "";
            }
            return deviceIpAddress;
        }

        protected void onPostExecute(String string) {
            Lg.d("deviceIpAddress", string);
        }
    }

0
说实话,我只对代码安全有一点了解,所以这可能有些hack。但对我来说,这是最通用的方法:
package com.my_objects.ip;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class MyIpByHost 
{
  public static void main(String a[])
  {
   try 
    {
      InetAddress host = InetAddress.getByName("nameOfDevice or webAddress");
      System.out.println(host.getHostAddress());
    } 
   catch (UnknownHostException e) 
    {
      e.printStackTrace();
    }
} }

InetAddress会返回当前设备连接的设备的IP而不是当前设备的IP吗? - Stigma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接