有人能告诉我如何以编程方式在Android中找到连接到同一网络的所有系统的IP地址。 DHCPInfo类仅提供分配给我们的Android设备的ipaddress,但不提供连接到同一网络的其他设备。如何获得连接到同一网络的其他设备的ipaddress?
答案 0 :(得分:5)
首先通过此
获取主机IPpublic 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是主机IP
现在通过此
连接ipsString 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);
}
答案 1 :(得分:-1)
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());
}
}
}
}