是否可以使用一些代码获得设备的IP地址?
当前回答
根据我的测试,这是我的建议
import java.net.*;
import java.util.*;
public class hostUtil
{
public static String HOST_NAME = null;
public static String HOST_IPADDRESS = null;
public static String getThisHostName ()
{
if (HOST_NAME == null) obtainHostInfo ();
return HOST_NAME;
}
public static String getThisIpAddress ()
{
if (HOST_IPADDRESS == null) obtainHostInfo ();
return HOST_IPADDRESS;
}
protected static void obtainHostInfo ()
{
HOST_IPADDRESS = "127.0.0.1";
HOST_NAME = "localhost";
try
{
InetAddress primera = InetAddress.getLocalHost();
String hostname = InetAddress.getLocalHost().getHostName ();
if (!primera.isLoopbackAddress () &&
!hostname.equalsIgnoreCase ("localhost") &&
primera.getHostAddress ().indexOf (':') == -1)
{
// Got it without delay!!
HOST_IPADDRESS = primera.getHostAddress ();
HOST_NAME = hostname;
//System.out.println ("First try! " + HOST_NAME + " IP " + HOST_IPADDRESS);
return;
}
for (Enumeration<NetworkInterface> netArr = NetworkInterface.getNetworkInterfaces(); netArr.hasMoreElements();)
{
NetworkInterface netInte = netArr.nextElement ();
for (Enumeration<InetAddress> addArr = netInte.getInetAddresses (); addArr.hasMoreElements ();)
{
InetAddress laAdd = addArr.nextElement ();
String ipstring = laAdd.getHostAddress ();
String hostName = laAdd.getHostName ();
if (laAdd.isLoopbackAddress()) continue;
if (hostName.equalsIgnoreCase ("localhost")) continue;
if (ipstring.indexOf (':') >= 0) continue;
HOST_IPADDRESS = ipstring;
HOST_NAME = hostName;
break;
}
}
} catch (Exception ex) {}
}
}
其他回答
在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());
一个设备可能有几个IP地址,在一个特定的应用程序中使用的IP地址可能不是接收请求的服务器将看到的IP地址。事实上,一些用户使用VPN或Cloudflare Warp等代理。
如果你的目的是获得IP地址,就像服务器从你的设备接收请求一样,那么最好是通过Java客户端查询IP地理定位服务,如Ipregistry(免责声明:我为该公司工作):
https://github.com/ipregistry/ipregistry-java
IpregistryClient client = new IpregistryClient("tryout");
RequesterIpInfo requesterIpInfo = client.lookup();
requesterIpInfo.getIp();
除了使用非常简单之外,您还可以获得其他信息,例如国家、语言、货币、设备IP的时区,并且您可以识别用户是否正在使用代理。
这是互联网上最简单的方法…… 首先,将此权限添加到您的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(); }
最近,一个IP地址仍然由getLocalIpAddress()返回,尽管与网络断开连接(没有服务指示器)。说明“设置>关于话机>状态”中显示的IP地址与应用程序想象的不一致。
我之前已经通过添加以下代码实现了一个解决方案:
ConnectivityManager cm = getConnectivityManager();
NetworkInfo net = cm.getActiveNetworkInfo();
if ((null == net) || !net.isConnectedOrConnecting()) {
return null;
}
有谁听过吗?
虽然有一个正确的答案,我在这里分享我的答案,希望这样会更方便。
WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
int ipAddress = wifiInf.getIpAddress();
String ip = String.format("%d.%d.%d.%d", (ipAddress & 0xff),(ipAddress >> 8 & 0xff),(ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff));
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在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)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?