admin管理员组文章数量:1531663
2024年3月25日发(作者:)
Android 手机上获取手机当前上网IP地址
(手机网关给手机号分配的IP)
每个手机上网通过移动网关的时候,网关都会给该手机号分配一个IP地址(当然这个IP地
址会在下线上线后会改变,网关都有记录的)
现在做的应用需要获取该IP地址,提交给服务器,代码如下:
[java] view plaincopy
1. /**
2. * 用来获取手机拨号上网(包括CTWAP和CTNET)时由PDSN分配给手机终端的源IP地址。
3. *
4. * @return
5. * @author SHANHY
6. */
7. public static String getPsdnIp() {
8. try {
9. for (Enumeration
nterfaces(); eElements();) {
10. NetworkInterface intf = ement();
11. for (Enumeration
(); eElements();) {
12. InetAddress inetAddress = ement();
13. if (!backAddress()) {
14. return tAddress().toString();
15. }
16. }
17. }
18. } catch (Exception e) {
19. }
20. return "";
21. }
如上这样写,在有些情况下就会有问题了,比如我现在用的是安卓4.0系统的手机,按上面
的方法默认会先获取到ipv6的地址,有时候我们只想要ipv4的地址,就需要再多做个类型
判断,代码如下:
[java] view plaincopy
1. /**
2. * 用来获取手机拨号上网(包括CTWAP和CTNET)时由PDSN分配给手机终端的源IP地址。
3. *
4. * @return
5. * @author SHANHY
6. */
7. public static String getPsdnIp() {
8. try {
9. for (Enumeration
nterfaces(); eElements();) {
10. NetworkInterface intf = ement();
11. for (Enumeration
(); eElements();) {
12. InetAddress inetAddress = ement();
13. if (!backAddress() && inetAddress instance
of Inet4Address) {
14. //if (!backAddress() && inetAddress instan
ceof Inet6Address) {
15. return tAddress().toString();
16. }
17. }
18. }
19. } catch (Exception e) {
20. }
21. return "";
22. }
版权声明:本文标题:Android手机上获取手机当前上网IP地址 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1711377460a306672.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论