Android 怎么获取手机端的ip地址

本文介绍如何使用Java代码在手机端获取本地ip地址,通过遍历网络接口并过滤掉环回地址来实现。

在和服务器互动的时候,常常会用到客户端ip地址。当然,在服务器端可以获取请求过来的ip,在手机端,怎么获取自己的ip呢?请参阅下面的函数:

view plain

public static String GetHostIp {

try {

for (Enumeration<NetworkInterface> en = NetworkInterface

.getNetworkInterfaces; en.hasMoreElements;) {

NetworkInterface intf = en.nextElement;

for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses; ipAddr

.hasMoreElements;) {

InetAddress inetAddress = ipAddr.nextElement;

if (!inetAddress.isLoopbackAddress) {

return inetAddress.getHostAddress;

}

}

}

} catch (SocketException ex) {

} catch (Exception e) {

}

return null;

}

其实,上面的方法通过java.net下的相关类获取ip的。主要用到的类有:java.net.NetworkInterface和java.net.InetAddress

在Java中获取手机端IP地址有多种方法,以下为你介绍两种常见的方式: ### 通过WifiManager获取(需在Android环境) 当手机连接WiFi时,可以使用`WifiManager`来获取IP地址。示例代码如下: ```java import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.widget.TextView; public class IPUtils { public void getIp(Context context, TextView get_ip_show) { //获取wifi服务 WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); //判断wifi是否开启 if (!wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(true); } WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); String ip = intToIp(ipAddress); get_ip_show.setText(ip); } //将IP地址改为标准的形式 private String intToIp(int i) { return (i & 0xFF ) + "." + ((i >> 8 ) & 0xFF) + "." + ((i >> 16 ) & 0xFF) + "." + ( i >> 24 & 0xFF); } } ``` 在上述代码中,首先获取`WifiManager`服务,判断WiFi是否开启,若未开启则开启WiFi。接着获取当前连接的WiFi信息,得到IP地址的整数形式,最后将其转换为标准的IP地址字符串形式并显示在指定的`TextView`上 [^1]。 ### 通过NetworkInterface获取 可以通过遍历网络接口来获取非回环地址IP地址,示例代码如下: ```java import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class IPUtils { public static String GetHostIp() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr.hasMoreElements();) { InetAddress inetAddress = ipAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress(); } } } } catch (SocketException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } } ``` 此代码通过`NetworkInterface.getNetworkInterfaces()`获取所有网络接口,然后遍历每个接口的所有IP地址,排除回环地址后返回第一个非回环地址IP [^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值