Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.net.InetAddress;

import java.net.UnknownHostException;

import android.content.Context;

import android.net.DhcpInfo;

import android.net.wifi.WifiManager;

import android.widget.Toast;

public class Main {
    public static String getDhcpIpString(Context mContext) {
        WifiManager mWifiManager;
        String broadcastIp = null;
        mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        if (mWifiManager.isWifiEnabled()) {
            DhcpInfo myDhcpInfo = mWifiManager.getDhcpInfo();
            if (myDhcpInfo == null) {
                Toast.makeText(mContext, "can not get dhcp info", Toast.LENGTH_SHORT).show();
                return null;
            } else {
                try {
                    broadcastIp = getBroadcastAddress(myDhcpInfo).getHostAddress();
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return null;
                }
            }
            return broadcastIp;
        }
        return null;
    }

    private static InetAddress getBroadcastAddress(DhcpInfo mDhcpInfo) throws UnknownHostException {
        int broadcast = (mDhcpInfo.ipAddress & mDhcpInfo.netmask) | ~mDhcpInfo.netmask;
        byte[] quads = new byte[4];
        try {
            for (int k = 0; k < 4; k++)
                quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return InetAddress.getByAddress(quads);
    }
}