有人可以告诉我如何以编程方式在 Android 中找到连接到同一网络的所有系统的 IP 地址。DHCPInfo 类仅提供分配给我们的 android 设备的 IP 地址,但不提供连接到同一网络的其他设备的 IP 地址。如何获取连接到同一网络的其他设备的IP地址?
问问题
12512 次
2 回答
5
首先通过这个获取主机ip
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 是主机 ip
现在通过这个获取连接的ips
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);
整顿
public String intToIp(int i) {
return (i & 0xFF) + "." +
((i >> 8 ) & 0xFF) + "." +
((i >> 16) & 0xFF) + "." +
((i >> 24) & 0xFF);
}
于 2014-01-13T12:40:37.147 回答
-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());
}
}
}
}
于 2013-04-16T12:00:43.653 回答