package com.jason.demo.androidip; import android.content.Context; import android.net.DhcpInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.text.format.Formatter; public class IPAddress { public String getIPAddress(Context ctx){ //获取wifi服务 WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); //判断wifi是否开启 如果没有开启 此方法会开启wifi if (!wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(true); } WifiManager wifi_service = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE); DhcpInfo dhcpInfo = wifi_service.getDhcpInfo(); WifiInfo wifiinfo = wifi_service.getConnectionInfo(); System.out.println("Wifi info----->"+wifiinfo.getIpAddress()); System.out.println("DHCP info gateway----->"+Formatter.formatIpAddress(dhcpInfo.gateway)); System.out.println("DHCP info netmask----->"+Formatter.formatIpAddress(dhcpInfo.netmask)); //DhcpInfo中的ipAddress是一个int型的变量,通过Formatter将其转化为字符串IP地址 return Formatter.formatIpAddress(dhcpInfo.ipAddress); } } 最后要说的是 添加权限
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.INTERNET"/>
时间: 2024-10-30 15:04:14