博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android 获取本机IP地址
阅读量:7228 次
发布时间:2019-06-29

本文共 1284 字,大约阅读时间需要 4 分钟。

hot3.png

private String getLocalIPAddress() throws SocketException{      for(Enumeration
en = NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){ NetworkInterface intf = en.nextElement(); for(Enumeration
enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){ InetAddress inetAddress = enumIpAddr.nextElement(); if(!inetAddress.isLoopbackAddress())){ return inetAddress.getHostAddress().toString(); } } } return "null"; }

但是,在android4.0以上系统中,上面的代码仅能够返回一个ipv6的地址,如果需要获取ip v4的地址,可以这么更改:

private String getLocalIPAddress() throws SocketException{      for(Enumeration
en = NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){ NetworkInterface intf = en.nextElement(); for(Enumeration
enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){ InetAddress inetAddress = enumIpAddr.nextElement(); if(!inetAddress.isLoopbackAddress() &&
(inetAddress instanceof Inet4Address)){ return inetAddress.getHostAddress().toString(); } } } return "null"; }

转载于:https://my.oschina.net/u/140714/blog/180904

你可能感兴趣的文章
线程信息的获取和设置
查看>>
Databricks Scala 编程风格指南
查看>>
Tkinter,label内容随多选框变化
查看>>
PHP开发中的数据类型 ( 第3篇 ) :Heaps
查看>>
网络七层协议
查看>>
4种删除Word空白页的小技巧,都是你需要用到的!
查看>>
单服务器MySQL主从复制实践
查看>>
CentOS 7 root口令恢复
查看>>
| 刘知远:让计算机听懂人话
查看>>
苹果收购初创公司Tueo Health,哮喘监测或将应用到Apple Watch
查看>>
CLR存储过程
查看>>
初级运维(一)
查看>>
C语言字符串常用函数学习(一)
查看>>
Lync Server 2010部署与应用(三)---拓扑生成与发布
查看>>
安全摘记1:关于安全与黑客
查看>>
我的友情链接
查看>>
tbox中vector容器的使用
查看>>
一个简单的PHP笔试题
查看>>
firebug重新载入页面获取源码
查看>>
我的友情链接
查看>>