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 en = workI

nterfaces(); eElements();) {

10. NetworkInterface intf = ement();

11. for (Enumeration enumIpAddr = tAddresses

(); 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 en = workI

nterfaces(); eElements();) {

10. NetworkInterface intf = ement();

11. for (Enumeration enumIpAddr = tAddresses

(); 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. }

本文标签: 手机获取IP地址网关上网