doum
7 天以前 2b287056e2f59518888d05a1bbc7e5a55fbd84d5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.doumee.keyCabinet.http;
 
/**
 * Created by MSI on 2018/5/22.
 */
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
 
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
 
/**
 * =======================================================
 * 版权:Copyright LiYing 2015-2016. All rights reserved.
 * 作者:liying - liruoer2008@yeah.net
 * 日期:2016/12/19 19:43
 * 版本:1.0
 * 描述:IP地址工具类
 * 备注:
 * =======================================================
 */
public class IPUtils {
 
    /**
     * 获取本机IPv4地址
     *
     * @param context
     * @return 本机IPv4地址;null:无网络连接
     */
    public static String getIpAddress(Context context) {
        try {
            // 获取WiFi服务
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            // 判断WiFi是否开启
            if (wifiManager.isWifiEnabled()) {
                // 已经开启了WiFi
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int ipAddress = wifiInfo.getIpAddress();
                String ip = intToIp(ipAddress);
                return ip;
            } else {
                // 未开启WiFi
                return getIpAddress();
            }
        }catch (Exception e){
            return "";
        }
    }
 
    private static String intToIp(int ipAddress) {
        return (ipAddress & 0xFF) + "." +
                ((ipAddress >> 8) & 0xFF) + "." +
                ((ipAddress >> 16) & 0xFF) + "." +
                (ipAddress >> 24 & 0xFF);
    }
 
    /**
     * 蜂窝移动数据已开启
     * 获取本机IPv4地址
     *
     * @return 本机IPv4地址;null:无网络连接
     */
    private static String getIpAddress() {
        try {
            NetworkInterface networkInterface;
            InetAddress inetAddress;
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                networkInterface = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
            return null;
        } catch (SocketException ex) {
            ex.printStackTrace();
            return null;
        }
    }
}