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(); ?