Reputation: 135
Can someone tell me how to find the IP addrss of all the systems connected to same network in Android programatically. DHCPInfo class gives only the ipaddress assigned to our android device but not for the other devices connected to the same network. How to get ipaddress of other devices connected to same network?
Upvotes: 3
Views: 14109
Reputation: 3255
First get the host ip by this
public String s_dns1 ;
public String s_dns2;
public String s_gateway;
public String s_ipAddress;
public String s_leaseDuration;
public String s_netmask;
public String s_serverAddress;
TextView info;
DhcpInfo d;
WifiManager wifii;
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);
d.dns1 is host ip
Now get connected ips by this
String connections = "";
InetAddress host;
try
{
host = InetAddress.getByName(intToIp(d.dns1));
byte[] ip = host.getAddress();
for(int i = 1; i <= 254; i++)
{
ip[3] = (byte) i;
InetAddress address = InetAddress.getByAddress(ip);
if(address.isReachable(100))
{
System.out.println(address + " machine is turned on and can be pinged");
connections+= address+"\n";
}
else if(!address.getHostAddress().equals(address.getHostName()))
{
System.out.println(address + " machine is known in a DNS lookup");
}
}
}
catch(UnknownHostException e1)
{
e1.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println(connections);
intToIp
public String intToIp(int i) {
return (i & 0xFF) + "." +
((i >> 8 ) & 0xFF) + "." +
((i >> 16) & 0xFF) + "." +
((i >> 24) & 0xFF);
}
Upvotes: 5
Reputation: 7092
private class Task extends AsyncTask<void void="">{
InetAddress[] inetAddress = null;
List<string> hostList = new ArrayList<string>();
@Override
protected Void doInBackground(Void... arg0) {
doTest();
}
@Override
protected void onPostExecute(Void result) {
ArrayAdapter<string> adapter
= new ArrayAdapter<string>(
AndroidInetActivity.this,
android.R.layout.simple_list_item_1,
hostList);
resultList.setAdapter(adapter);
}
private void doTest(){
String host = hostinput.getText().toString();
inetAddress = InetAddress.getAllByName(host);
for(int i = 0; i < inetAddress.length; i++){
hostList.add(inetAddress[i].getClass() + " -\n"
+ inetAddress[i].getHostName() + "\n"
+ inetAddress[i].getHostAddress());
}
}
}
}
Upvotes: -1