Android 怎么获取手机端的ip地址
答案:2 悬赏:80 手机版
解决时间 2021-02-18 15:33
- 提问者网友:玫瑰园
- 2021-02-17 23:16
Android 怎么获取手机端的ip地址
最佳答案
- 五星知识达人网友:人间朝暮
- 2021-02-18 00:12
在和服务器互动的时候,常常会用到客户端ip地址。当然,在服务器端可以获取请求过来的ip,在手机端,怎么获取自己的ip呢?请参阅下面的函数:
[java] public static String GetHostIp() {
try {
for (Enumeration en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration ipAddr = intf.getInetAddresses(); ipAddr
.hasMoreElements();) {
InetAddress inetAddress = ipAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
} catch (Exception e) {
}
return null;
}
public static String GetHostIp() {
try {
for (Enumeration en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration 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] public static String GetHostIp() {
try {
for (Enumeration
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration
.hasMoreElements();) {
InetAddress inetAddress = ipAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
} catch (Exception e) {
}
return null;
}
public static String GetHostIp() {
try {
for (Enumeration
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration
.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
全部回答
- 1楼网友:酒醒三更
- 2021-02-18 00:45
1.使用wifi
首先设置用户权限
其次,代码如下
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
//获取wifi服务
wifimanager wifimanager = (wifimanager) getsystemservice(context.wifi_service);
//判断wifi是否开启
if (!wifimanager.iswifienabled()) {
wifimanager.setwifienabled(true);
}
wifiinfo wifiinfo = wifimanager.getconnectioninfo();
int ipaddress = wifiinfo.getipaddress();
string ip = inttoip(ipaddress);
edittext et = (edittext)findviewbyid(r.id.edittext01);
et.settext(ip);
}
private string inttoip(int i) {
return (i & 0xff ) + "." +
((i >> 8 ) & 0xff) + "." +
((i >> 16 ) & 0xff) + "." +
( i >> 24 & 0xff) ;
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯