I'm developing an Android application, I have to discover each hosts in a WiFi network, I have implemented a function that "ping" all IP address between 1 and 255 of a certain network.
This solution it work perfectly, but there is a problem, the execution time.. Every time that i start my application I wait about 256 second, it too long, i can't wait this time.
This is my source code (i found this code on Stack, i modified the code to work in my condition):
public class ScanNetwork {
ArrayList < String > hosts;
int i;
boolean finish = false;
public ArrayList < String > ScanNetwork(String ipAddress) {
hosts = new ArrayList < String > ();
final String subnet = ipAddress.substring(0, ipAddress.lastIndexOf("."));
for (i = 0; i < 256; i++) {
String currentHost = subnet + "." + i;
Process p1 = null;
int returnVal = 0;
try {
p1 = Runtime.getRuntime().exec("ping -w 50 -c 1 " + currentHost);
returnVal = p1.waitFor();
} catch (IOException e) {
System.out.println("Log: " + e.toString());
} catch (InterruptedException e) {
System.out.println("Log: " + e.toString());
}
boolean reachable = (returnVal == 0);
if (reachable) {
if (!hosts.contains(currentHost)) {
hosts.add(currentHost);
System.out.println(currentHost);
}
}
}
return hosts;
}
}
This source code is perfect but the execution time is excessive, there are other way to obtain all the host in the network ?
How i can solve this problem ?
The problem I see is that you are doing all the pings sequentially - the loop is spending most of its time waiting for replies. Try starting up a few AsyncTasks, each of which has an assigned range of addresses to search, and let them work in parallel.
Note that for a typical 192.168.1.x network, ".0" (all 0 bits) ".255" (all 1 bits) will not correspond to a host and doesn't need checking.
Also don't forget that not everybody responds to a ping (this is more likely in a corporate network, less so at home)
Related
I have to create a program that sniff a local network for school. I chose to work with Java and found out that you can capture packets with jpcap.
So I wanted to follow one of the example provided in jpcap's github and it seems like I can only find my own packets.
Like I said, I've looked at the code and chose my wifi interface. The program is capturing packets and I put all the source ip addresses in a text file to run some tests. I have also created a hashmap the ip addresses I've finded when I did a arp -a. From what I've read online, this command shows you ip addresses in your network.I created a boolean set to false and I then proceeded to run a loop that goes through the textfile and looked if the ip address was in the hashMap : if one of the addresses appeared in the hashmap, the boolean would be change to true and it would mean that I've managed to catch something.
After running the test, the boolean came out false.
Here's the example code
``public class PacketCaptor {
private static final int INFINITE = -1;
private static final int PACKET_COUNT = INFINITE;
/*
private static final String HOST = "203.239.110.20";
private static final String FILTER =
"host " + HOST + " and proto TCP and port 23";
*/
private static final String FILTER =
// "port 23";
"";
public static void main(String[] args) {
try {
if(args.length == 1){
PacketCaptor sniffer = new PacketCaptor(args[0]);
} else {
System.out.println("Usage: java Sniffer [device name]");
System.out.println("Available network devices on your machine:");
String[] devs = PacketCapture.lookupDevices();
for(int i = 0; i < devs.length ; i++)
System.out.println("\t" + devs[i]);
}
} catch(Exception e) {
e.printStackTrace();
}
}
public PacketCaptor(String device) throws Exception {
// Initialize jpcap
PacketCapture pcap = new PacketCapture();
System.out.println("Using device '" + device + "'");
pcap.open(device, true);
//pcap.setFilter(FILTER, true);
pcap.addPacketListener(new PacketHandler());
System.out.println("Capturing packets...");
pcap.capture(PACKET_COUNT);
}
}
class PacketHandler implements PacketListener
{
WritingClass writing = new WritingClass();
public void packetArrived(Packet packet) {
try {
// only handle TCP packets
if(packet instanceof TCPPacket) {
TCPPacket tcpPacket = (TCPPacket)packet;
byte[] data = tcpPacket.getTCPData();
String srcHost = tcpPacket.getSourceAddress();
String dstHost = tcpPacket.getDestinationAddress();
String isoData = new String(data, "ISO-8859-1");
System.out.println(srcHost+" -> " + dstHost + ": " + isoData);
String datas = srcHost+"|"+dstHost+"|";
writing.write(datas, this.writing.getFileName());
}
} catch( Exception e ) {
e.printStackTrace();
}
}
Can anyone help me figure out why It doesn't work ?
Thank you so much for your help
The reason why you aren't able to capture more packets is because you need an interface in promisc or raw mode, I advice you to use a proper sniffer like wireshark to check if other packets that aren't addressed to you can be captured. If not, means you need apply a mitm method because you are in a commuted network. For use that code on wifi should be enough an interface in monitor mode (check aircrack-ng suite).
In GNU/Linux Debian based systems may use the command iw dev wlan0 interface add mon0 type monitor (from package wireless-tools)
InetAddress byName = InetAddress.getByName("173.39.161.140");
System.out.println(byName);
System.out.println(byName.isReachable(1000));
Why does isReachable return false? I can ping the IP.
The "isReachable" method has not been worthy of using for me in many cases. You can scroll to the bottom to see my alternative for simply testing if you're online and capable of resolving external hosts (i.e. google.com) ... Which generally seems to work on *NIX machines.
The issue
There is alot of chatter about this :
Here are other, similar questions :
Detect internet Connection using Java
How do I test the availability of the internet in Java?
And even a reported bug on this same matter :
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4921816
Part 1 : A reproducible example of the problem
Note that in this case, it fails.
//also, this fails for an invalid address, like "www.sjdosgoogle.com1234sd"
InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
for (InetAddress address : addresses) {
if (address.isReachable(10000))
{
System.out.println("Connected "+ address);
}
else
{
System.out.println("Failed "+address);
}
}
//output:*Failed www.google.com/74.125.227.114*
Part 2 : A Hackish Workaround
As an alternative, you can do this :
// in case of Linux change the 'n' to 'c'
Process p1 = java.lang.Runtime.getRuntime().exec("ping -n 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
The -c option of ping will allow ping to simply try to reach the server once(as opposed to the infinite ping which we're used to using at the terminal).
This will return 0 if the host is reachable. Otherwise, you will get "2" as a return value.
Much simpler - but of course it is platform specific.
And there may be certain privilege caveats to using this command - but I find it works on my machines.
PLEASE Note that :
1) This solution is not production quality. Its a bit of a hack. If google is down, or your internet is temporarily slow, or maybe even if there is some funniness in your privileges/system settings, if could return false negatives (i.e. it could fail even though the input address is reachable).
2) The isReachable failure is an outstanding issue. Again - there are several online resources indicating that there is no "perfect" way of doing this at the time of this writing, due to the way the JVM tries to reach hosts - I guess it is an intrinsically platform specific task which, although simple, hasn't yet been abstracted sufficiently by the JVM.
I came here to get an answer for this same question, but I was unsatisfied by any of the answers because I was looking for a platform independent solution. Here is the code which I wrote and is platform independent, but requires information about any open port on the other machine (which we have most of the time).
private static boolean isReachable(String addr, int openPort, int timeOutMillis) {
// Any Open port on other machine
// openPort = 22 - ssh, 80 or 443 - webserver, 25 - mailserver etc.
try {
try (Socket soc = new Socket()) {
soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis);
}
return true;
} catch (IOException ex) {
return false;
}
}
Update: Based on a recent comment to this answer, here is a succinct version of the above code:
private static boolean isReachable(String addr, int openPort, int timeOutMillis) {
// Any Open port on other machine
// openPort = 22 - ssh, 80 or 443 - webserver, 25 - mailserver etc.
try (Socket soc = new Socket()) {
soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis);
return true;
} catch (IOException ex) {
return false;
}
}
If you only want to check if it is connected to internet use this method , It returns true if internet is connected, Its preferable if you use the address of the site you are trying to connect through the program.
public static boolean isInternetReachable()
{
try {
//make a URL to a known source
URL url = new URL("http://www.google.com");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
Just mentioning it explicitly since the other answers don't. The ping part of isReachable() requires root access on Unix. And as pointed out by bestsss in 4779367:
And if you ask why ping from bash doesn't, actually it does need as well. Do that ls -l /bin/ping.
Since using root was not an option in my case the solution was to allow access to port 7 in the firewall to the specific server I was interested in.
I am not sure what was the state when the original question was asked back in 2012.
As it stands now, ping will be executed as a root. Through the ping executable's authorization you will see the +s flag, and the process belonging to root, meaning it will run as root. run ls -liat on where the ping is located and you should see it.
So, if you run InetAddress.getByName("www.google.com").isReacheable(5000) as root, it should return true.
you need proper authorizations for the raw socket, which is used by ICMP (the protocol used by ping)
InetAddress.getByName is as reliable as ping, but you need proper permissions on the process to have it running properly.
Since you can ping the computer, your Java process should run with sufficient privileges to perform the check. Probably due to use of ports in the lower range. If you run your java program with sudo/superuser, I'll bet it works.
I would suggest that the ONLY reliable way to test an internet connection is to actually connect AND download a file, OR to parse the output of an OS ping call via exec(). You cannot rely on the exit code for ping and isReachable() is crap.
You cannot rely on a ping exit code as it returns 0 if the ping command executes correctly. Unfortunately, ping executes correctly if it can't reach the target host but gets a "Destination host unreachable" from your home ADSL router. This is kind of a reply that gets treated as a successfull hit, thus exit code = 0. Have to add though that this is on a Windows system. Not checked *nixes.
private boolean isReachable(int nping, int wping, String ipping) throws Exception {
int nReceived = 0;
int nLost = 0;
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("ping -n " + nping + " -w " + wping + " " + ipping);
Scanner scanner = new Scanner(process.getInputStream());
process.waitFor();
ArrayList<String> strings = new ArrayList<>();
String data = "";
//
while (scanner.hasNextLine()) {
String string = scanner.nextLine();
data = data + string + "\n";
strings.add(string);
}
if (data.contains("IP address must be specified.")
|| (data.contains("Ping request could not find host " + ipping + ".")
|| data.contains("Please check the name and try again."))) {
throw new Exception(data);
} else if (nping > strings.size()) {
throw new Exception(data);
}
int index = 2;
for (int i = index; i < nping + index; i++) {
String string = strings.get(i);
if (string.contains("Destination host unreachable.")) {
nLost++;
} else if (string.contains("Request timed out.")) {
nLost++;
} else if (string.contains("bytes") && string.contains("time") && string.contains("TTL")) {
nReceived++;
} else {
}
}
return nReceived > 0;
}
nping is number of try to ping ip(packets), if you have busy network or systems choose biger nping numbers.
wping is time waiting for pong from ip, you can set it 2000ms
for using this method u can write this:
isReachable(5, 2000, "192.168.7.93");
Or using this way:
public static boolean exists(final String host)
{
try
{
InetAddress.getByName(host);
return true;
}
catch (final UnknownHostException exception)
{
exception.printStackTrace();
// Handler
}
return false;
}
InetAddress.isReachable is flappy, and sometimes returns unreachable for addresses which we can ping.
I tried the following:
ping -c 1 <fqdn> and check the exit status.
Works for all the cases i had tried where InetAddress.isReachable doesn't work.
To Check Internet
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
//You can replace it with your name
return !ipAddr.equals("");
} catch (Exception e1) {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("/system/bin/ping -W 1 -c 1 www.google.com");
int returnVal = 0;
returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e2) {
e2.printStackTrace();
return false;
}
}
}
To check network connectivity
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
Because isReachable is using the TCP protocol(by WireShark) The Ping command is using ICMP protocol,if you want to return true you need to open the 7 port
we were wanting to build a functionality where if a user is connected to a WiFi network, we can display the details of other devices connected to the same WiFi. How do we go about it?
Right now, we are able to achieve it by:
pinging all the IP addresses on the current network(looping from 1-255) - this is the most time consuming step (code snippet below)
for the IP addresses that responded, fetching their MAC addresses and finally
fetching the manufacturer for the MAC addresses using an external API
we have success in this but the issue is that it takes way too long - around 4-5 minutes to do this. I have a feeling that someone can point us towards a better, faster solution.
There was a similar question(although it was about iOS) but didn't find any answer, hence posting this again. Please pardon if that was against the rules. Any help in this would be highly appreciated.
Here's the snippet of code which is taking too long to give the results back(step 1)
for (int i = 0; i < 255; i++) {
String host = "";
try {
String subnet = "192.168.2";
host = subnet + "." + i;
Process exec = Runtime.getRuntime().exec(String.format(CMD, host));
int i1 = exec.waitFor();
if (i1 == 0) {
InetAddress a = InetAddress.getByName(host);
Log.i("TAG", "run: " + a.getHostAddress());
} else {
throw new IOException("Unable to get ping from runtime");
}
} catch (IOException | InterruptedException e) {
try {
InetAddress a = InetAddress.getByName(host);
if (a.isReachable(200)) {
Log.i("TAG", "run: " + a.getHostAddress());
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
I'm trying to create a simple AMQP application in Java. The application should simply bounce a number between two clients. Each time the number is received the client should add 1 to it and send it back to the other client. However, I cannot get the example to work at all. I can send the first number, but it is never received. In the webinterface of the broker I see zero connections and messages. I am doing something wrong, but can't figure out what it is. Hopefully someone here can spot the error(s). Below is the code I've written.
Messenger mng = Proton.messenger();
mng.start();
mng.subscribe("localhost:5672");
Message msg = Proton.message();
msg.setAddress("localhost:5672");
msg.setSubject("foobar");
if (args.length > 2 && args[2].equals("foo"))
{
System.out.println("Sending initial: 1");
msg.setBody(new AmqpValue("1"));
mng.put(msg);
mng.send();
System.out.println("Sent initial: 1");
}
try
{
while (true)
{
mng.recv(1);
while(mng.incoming() > 0) {
Message message = mng.get();
int consumed = Integer.parseInt(message.getBody().toString());
System.out.println("Received: " + consumed);
consumed = consumed % 100;
if (consumed == 0)
{
long seconds = (System.currentTimeMillis() - start) / 1000;
start = System.currentTimeMillis();
System.out.println("Last hundred messages took (s): " + seconds);
}
msg.setBody(new AmqpValue(""+(consumed+1)));
mng.put(msg);
mng.send();
}
}
}
catch (Exception e)
{
System.out.println("proton error: " + e.getMessage());
}
Well, I turned off my firewall completely and changed the code a bit to listen and subscribe to my local IP address and that worked well for me:
Messenger mng = Proton.messenger();
mng.start();
mng.subscribe("amqp://~xxx.xxx.xxx.xxx");
Message msg = Proton.message();
msg.setAddress("amqp://yyy.yyy.yyy.yyy");
....
InetAddress byName = InetAddress.getByName("173.39.161.140");
System.out.println(byName);
System.out.println(byName.isReachable(1000));
Why does isReachable return false? I can ping the IP.
The "isReachable" method has not been worthy of using for me in many cases. You can scroll to the bottom to see my alternative for simply testing if you're online and capable of resolving external hosts (i.e. google.com) ... Which generally seems to work on *NIX machines.
The issue
There is alot of chatter about this :
Here are other, similar questions :
Detect internet Connection using Java
How do I test the availability of the internet in Java?
And even a reported bug on this same matter :
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4921816
Part 1 : A reproducible example of the problem
Note that in this case, it fails.
//also, this fails for an invalid address, like "www.sjdosgoogle.com1234sd"
InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
for (InetAddress address : addresses) {
if (address.isReachable(10000))
{
System.out.println("Connected "+ address);
}
else
{
System.out.println("Failed "+address);
}
}
//output:*Failed www.google.com/74.125.227.114*
Part 2 : A Hackish Workaround
As an alternative, you can do this :
// in case of Linux change the 'n' to 'c'
Process p1 = java.lang.Runtime.getRuntime().exec("ping -n 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
The -c option of ping will allow ping to simply try to reach the server once(as opposed to the infinite ping which we're used to using at the terminal).
This will return 0 if the host is reachable. Otherwise, you will get "2" as a return value.
Much simpler - but of course it is platform specific.
And there may be certain privilege caveats to using this command - but I find it works on my machines.
PLEASE Note that :
1) This solution is not production quality. Its a bit of a hack. If google is down, or your internet is temporarily slow, or maybe even if there is some funniness in your privileges/system settings, if could return false negatives (i.e. it could fail even though the input address is reachable).
2) The isReachable failure is an outstanding issue. Again - there are several online resources indicating that there is no "perfect" way of doing this at the time of this writing, due to the way the JVM tries to reach hosts - I guess it is an intrinsically platform specific task which, although simple, hasn't yet been abstracted sufficiently by the JVM.
I came here to get an answer for this same question, but I was unsatisfied by any of the answers because I was looking for a platform independent solution. Here is the code which I wrote and is platform independent, but requires information about any open port on the other machine (which we have most of the time).
private static boolean isReachable(String addr, int openPort, int timeOutMillis) {
// Any Open port on other machine
// openPort = 22 - ssh, 80 or 443 - webserver, 25 - mailserver etc.
try {
try (Socket soc = new Socket()) {
soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis);
}
return true;
} catch (IOException ex) {
return false;
}
}
Update: Based on a recent comment to this answer, here is a succinct version of the above code:
private static boolean isReachable(String addr, int openPort, int timeOutMillis) {
// Any Open port on other machine
// openPort = 22 - ssh, 80 or 443 - webserver, 25 - mailserver etc.
try (Socket soc = new Socket()) {
soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis);
return true;
} catch (IOException ex) {
return false;
}
}
If you only want to check if it is connected to internet use this method , It returns true if internet is connected, Its preferable if you use the address of the site you are trying to connect through the program.
public static boolean isInternetReachable()
{
try {
//make a URL to a known source
URL url = new URL("http://www.google.com");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
Just mentioning it explicitly since the other answers don't. The ping part of isReachable() requires root access on Unix. And as pointed out by bestsss in 4779367:
And if you ask why ping from bash doesn't, actually it does need as well. Do that ls -l /bin/ping.
Since using root was not an option in my case the solution was to allow access to port 7 in the firewall to the specific server I was interested in.
I am not sure what was the state when the original question was asked back in 2012.
As it stands now, ping will be executed as a root. Through the ping executable's authorization you will see the +s flag, and the process belonging to root, meaning it will run as root. run ls -liat on where the ping is located and you should see it.
So, if you run InetAddress.getByName("www.google.com").isReacheable(5000) as root, it should return true.
you need proper authorizations for the raw socket, which is used by ICMP (the protocol used by ping)
InetAddress.getByName is as reliable as ping, but you need proper permissions on the process to have it running properly.
Since you can ping the computer, your Java process should run with sufficient privileges to perform the check. Probably due to use of ports in the lower range. If you run your java program with sudo/superuser, I'll bet it works.
I would suggest that the ONLY reliable way to test an internet connection is to actually connect AND download a file, OR to parse the output of an OS ping call via exec(). You cannot rely on the exit code for ping and isReachable() is crap.
You cannot rely on a ping exit code as it returns 0 if the ping command executes correctly. Unfortunately, ping executes correctly if it can't reach the target host but gets a "Destination host unreachable" from your home ADSL router. This is kind of a reply that gets treated as a successfull hit, thus exit code = 0. Have to add though that this is on a Windows system. Not checked *nixes.
private boolean isReachable(int nping, int wping, String ipping) throws Exception {
int nReceived = 0;
int nLost = 0;
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("ping -n " + nping + " -w " + wping + " " + ipping);
Scanner scanner = new Scanner(process.getInputStream());
process.waitFor();
ArrayList<String> strings = new ArrayList<>();
String data = "";
//
while (scanner.hasNextLine()) {
String string = scanner.nextLine();
data = data + string + "\n";
strings.add(string);
}
if (data.contains("IP address must be specified.")
|| (data.contains("Ping request could not find host " + ipping + ".")
|| data.contains("Please check the name and try again."))) {
throw new Exception(data);
} else if (nping > strings.size()) {
throw new Exception(data);
}
int index = 2;
for (int i = index; i < nping + index; i++) {
String string = strings.get(i);
if (string.contains("Destination host unreachable.")) {
nLost++;
} else if (string.contains("Request timed out.")) {
nLost++;
} else if (string.contains("bytes") && string.contains("time") && string.contains("TTL")) {
nReceived++;
} else {
}
}
return nReceived > 0;
}
nping is number of try to ping ip(packets), if you have busy network or systems choose biger nping numbers.
wping is time waiting for pong from ip, you can set it 2000ms
for using this method u can write this:
isReachable(5, 2000, "192.168.7.93");
Or using this way:
public static boolean exists(final String host)
{
try
{
InetAddress.getByName(host);
return true;
}
catch (final UnknownHostException exception)
{
exception.printStackTrace();
// Handler
}
return false;
}
InetAddress.isReachable is flappy, and sometimes returns unreachable for addresses which we can ping.
I tried the following:
ping -c 1 <fqdn> and check the exit status.
Works for all the cases i had tried where InetAddress.isReachable doesn't work.
To Check Internet
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
//You can replace it with your name
return !ipAddr.equals("");
} catch (Exception e1) {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("/system/bin/ping -W 1 -c 1 www.google.com");
int returnVal = 0;
returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e2) {
e2.printStackTrace();
return false;
}
}
}
To check network connectivity
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
Because isReachable is using the TCP protocol(by WireShark) The Ping command is using ICMP protocol,if you want to return true you need to open the 7 port