[Android] After the mobile phone is connected to the hotspot, it will automatically obtain the IP of the hotspot

1. Permission

 <uses-permission android:name = "android.permission.ACCESS_WIFI_STATE"/>

2、java

WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
String serverIp = getIPv4Address(wifi.getDhcpInfo().serverAddress);
Config.IP = serverIp;
Log.i("djtest", "server ip = " + Config.IP);  // 自动获取IP

getIPv4Address function:

/**
     * 获取热点 Server IP
     * @param ipAddress
     * @return
     */
    public String getIPv4Address(int ipAddress) {
    
    
        // convert integer ip to a byte array
        byte[] tempAddress = BigInteger.valueOf(ipAddress).toByteArray();
        int size = tempAddress.length;
        // reverse the content of the byte array
        for(int i = 0; i < size/2; i++) {
    
    
            byte temp = tempAddress[size-1-i];
            tempAddress[size-1-i] = tempAddress[i];
            tempAddress[i] = temp;
        }

        try {
    
    
            // get the IPv4 formatted ip from the reversed byte array
            InetAddress inetIP = InetAddress.getByAddress(tempAddress);
            return inetIP.getHostAddress();
        } catch (UnknownHostException e) {
    
    
            e.printStackTrace();
        }
        return "";
    }

Guess you like

Origin blog.csdn.net/qq_30885821/article/details/108865658
Recommended