Twinone
Twinone

Reputation: 3029

Obtaining network IP Address in Android

I have a service that listens for a connection and I want it to listen only on a specific network. I can get my device's IP addresses like this:

    private void printNetworkInterfaces()
    {
        try
        {
            Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface ni : Collections.list(nis))
            {
                Enumeration<InetAddress> iis = ni.getInetAddresses();

                for (InetAddress ia : Collections.list(iis))
                {
                    // We only want IPv4 addresses
                    if (!isIPv4(ia.getHostAddress()))
                        continue;
                    // Do tomething with ia.getHostAddress();


                }
            }    
        }
        catch (SocketException e)
        {
            Log.w(TAG,e);
        }
    }

But instead of the IP of the device, i want the IP of the network to listen on that network. For example, if the IP were 192.168.1.1, then the network IP should be 192.168.1.0.

I could replace the 4th value with a 0 directly, but this would fail for other networks.

Is there some way to get the network address associated to the IP addres returned by InetAddress.getHostAddress(); ?

Upvotes: 0

Views: 3925

Answers (1)

Totoo
Totoo

Reputation: 139

From network mask and ip you can calculate the network ip.

wifii= (WifiManager) getSystemService(Context.WIFI_SERVICE);
 d=wifii.getDhcpInfo();
 s_dns1="DNS 1: "+String.valueOf(d.dns1);
 s_dns2="DNS 2: "+String.valueOf(d.dns2);    
 s_gateway="Default Gateway: "+String.valueOf(d.gateway);    
 s_ipAddress="IP Address: "+String.valueOf(d.ipAddress); 
 s_leaseDuration="Lease Time: "+String.valueOf(d.leaseDuration);     
 s_netmask="Subnet Mask: "+String.valueOf(d.netmask);    
 s_serverAddress="Server IP: "+String.valueOf(d.serverAddress);

Upvotes: 1

Related Questions