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 en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { networkInterface = en.nextElement(); for (Enumeration 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; } } }