是否可以使用一些代码获得设备的IP地址?
当前回答
请检查这个代码…使用此代码。我们将从移动互联网获得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();
}
}
}
其他回答
这是互联网上最简单的方法…… 首先,将此权限添加到您的manifest文件中…
“互联网” “ACCESS_NETWORK_STATE”
将此添加到Activity的onCreate文件中。
getPublicIP();
现在将这个函数添加到MainActivity.class中。
private void getPublicIP() { ArrayList<String> urls=new ArrayList<String>(); //to read each line new Thread(new Runnable(){ public void run(){ //TextView t; //to show the result, please declare and find it inside onCreate() try { // Create a URL for the desired page URL url = new URL("https://api.ipify.org/"); //My text file location //First open the connection HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.setConnectTimeout(60000); // timing out in a minute BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); //t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate() String str; while ((str = in.readLine()) != null) { urls.add(str); } in.close(); } catch (Exception e) { Log.d("MyTag",e.toString()); } //since we are in background thread, to post results we have to go back to ui thread. do the following for that PermissionsActivity.this.runOnUiThread(new Runnable(){ public void run(){ try { Toast.makeText(PermissionsActivity.this, "Public IP:"+urls.get(0), Toast.LENGTH_SHORT).show(); } catch (Exception e){ Toast.makeText(PermissionsActivity.this, "TurnOn wiffi to get public ip", Toast.LENGTH_SHORT).show(); } } }); } }).start(); }
编译一些想法,以更好的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()
请检查这个代码…使用此代码。我们将从移动互联网获得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();
}
}
}
在AndroidManifest.xml中声明ACCESS_WIFI_STATE权限:
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE"/>
可以通过WifiManager获取IP地址:
Context context = requireContext().getApplicationContext();
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
Kotlin极简版
fun getIpv4HostAddress(): String {
NetworkInterface.getNetworkInterfaces()?.toList()?.map { networkInterface ->
networkInterface.inetAddresses?.toList()?.find {
!it.isLoopbackAddress && it is Inet4Address
}?.let { return it.hostAddress }
}
return ""
}
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在Android中将字符串转换为Uri
- 如何在NestedScrollView内使用RecyclerView ?
- 移动到另一个EditText时,软键盘下一步点击Android
- Android应用中的GridView VS GridLayout
- Activity和FragmentActivity的区别
- 右对齐文本在android TextView
- 权限拒绝:start前台需要android.permission.FOREGROUND_SERVICE
- 如何更改android操作栏的标题和图标
- Android Split字符串
- 让一个链接在安卓浏览器启动我的应用程序?
- 如何在Android工作室的外部库中添加一个jar ?
- GridLayout(不是GridView)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?