Check Internet connection

FluFlu
edited July 2014 in How To...

What command should I use to check if the computer has an Internet connection? I looked up at the Network library and I thought I could try to connect to a server and if it fails then it means that it doesn't have an internet connection. The server would be a safe one like a Google server, but I'm not sure if that will always work properly. Any ideas?

Tagged:

Answers

  • edited July 2014 Answer ✓
    import java.io.InputStreamReader;
    StringBuilder sb=null;
    
        try {
          Process ping = Runtime.getRuntime().exec("ping " +" -c "+" 1 "+"www.google.com" );
          BufferedReader br = new BufferedReader(new InputStreamReader(ping.getInputStream()));
          sb = new StringBuilder();
          String line;
          while ( (line = br.readLine ()) != null) {
            sb.append(line);
            sb.append("\n");
          }
        } 
        catch (IOException e) {
          e.printStackTrace();
        }
        if ( sb.toString().trim().equals("")) {
    
         print("NO CONNECTION");
          System.exit(0);
        }
        System.out.println("connected...");
    

    i had written this for linux, i guess it is the same for mac, in windows i think the ping command is a bit different...

  • System.out.println(..) it's java.. also the other commands. There is no void setup() or void draw(). Is this working in processing?

  • This code would work find in Processing, as Processing is built on top of Java. Try something out before dismissing it.

    More generally, you need to understand what this code is doing and then customize it to fit your needs. Maybe you'd create a function that returns a boolean representing whether the network is connected, and instead of the print statements in the above code, you'd have return statements. It's up to you.

    Why do you need to check the internet connection? If you're attempting to access a resource on the web, chances are it will throw an Exception if it's unavailable, so you could just use that instead.

  • Yes, I want to acces a resource on the web, but how do I "customize" the Exception? Wouldn't it be simplier to check if there is Internet connection instead? This is what I thought.

  • Why do you need to customize any Exception? It'll throw an Exception if it can't be accessed. Just catch the Exception. You have to try stuff out before dismissing it.

  • Catch an Exception? Sorry but I don't know what really that means. Maybe just a vague idea, but nothing more.

  • Yes, I want to acces a resource on the web, but how do I "customize" the Exception? Wouldn't it be simplier to check if there is Internet connection instead? This is what I thought.

    did you run the code? why do you want to customize the Exception?

  • Yes, I ran the code and no matter what I have an Internet connection or not, no matter the URL is not valid, it always says "connected...".I tried to make a few changes but no effect. Her is what I need to do. I first want to check if it is an Internet connection. If it is not, a series of events happen. If it does, another different set of events happen. And I control that using boolean variables. For example, if it is a connection, a = true, else a = false. Then another if for the events.

  • Can you post an MCVE that demonstrates what you're trying to do? Not your whole sketch, but just enough so we can understand more accurately what you're doing.

  • edited July 2014

    are you sure that you disconnect before running it??

    try something else... use ping on a shell/terminal and check the results

    disconnect use ping again....

    also try to ping google dns servers (8.8.8.8, 8.8.4.4)

    if this works .....then i does not make sense :P after all it uses the same os command...

  • So here is the code:

    import com.onformative.yahooweather.*;
    
    YahooWeather weather;
    int updateIntervallMillis = 300000;
    
    void setup() {
      size(200,200);
    
      weather = new YahooWeather(this, 638242, "c", updateIntervallMillis);
      weather.update();
    
    }
    
    void draw() {
      weather.update();
      String weatherCondition = weather.getWeatherCondition();
    }
    

    What I'm trying to do is to put all this code into an if. That if determines if there is an available Internet connection. If it isn't, it diesplays on the screen "The service is unavailable".

  • I don't really know anything about the YahooWeather class. What does it do if there isn't an internet connection?

  • It throws a NullPointerException error.

  • Then simply catch that and you know you don't have internet.

  • What does it mean to catch something? I can't understand...

  • http://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html

    catch is explained a few pages in, but read it all.

    YahooWeather probably isn't throwing the NPE, it's returning a null and your weather.update() is causing the Exception. so you can just check for a null returned from the first call, no need to catch anything.

  • OK, I just read it and I understood it. But wouldn't the program be slower if I try to catch this error every time draw() executes? I think it would be better to put it in setup(), and so it executes only one time at the beginning? And one more question. For NullPointerException I put catch (NullPointerException e) { ... } Is that right? And in the try block I put the code with weather update that I want to see if it throws an Exception?

  • edited July 2014

    For NullPointerException I put catch...

    If it is your own code that throws a NullPointerException, it's bad programming catching it!
    Just make sure that a variable isn't null before accessing an object's member instead!!! [-(

  • Was the program slower when you tried it out? I guarantee that a try/catch or an if statement will be MUCH faster than whatever you're doing that accesses the internet. In fact, I wouldn't put the internet access step inside draw at all.

    You should look at the tutorials that have been posted and try something out, but the general syntax will look like this:

    try{
       //do something that might throw NPE
    }
    catch(NullPointerException npe){
       //uh oh, an NPE happened
    }
    
  • I looked at the tutorials and got the basic idea, but it just looks to good to be true. I mean, I expected to be something much more complicated and I have a feeling that something will eventually go wrong. So I will try it out to see how it is going. @GoToLoop It's not my own code that's generated the NPE. When I have internet connection, it works fine. When I don't, it throws NPE.

  • FluFlu
    edited July 2014

    Surprisingly, it works just fine! Thank you everyone for the help!

    import com.onformative.yahooweather.*;
    
    YahooWeather weather;
    int updateIntervallMillis = 300000;
    
    void setup() {
      size(200,200);
    
      weather = new YahooWeather(this, 638242, "c", updateIntervallMillis);
      weather.update();
    }
    
    void draw() {
      try {
      String weatherCondition = weather.getWeatherCondition();
      println(weatherCondition);
      }
      catch(NullPointerException npe) {
        println("An unhappy NPE just happened");
      } 
      println(frameRate);
    }
    
  • I'm not sure what the weather.update() function does, but it seems like you might want that in a timer?

    (Or maybe not, I have no idea what it does)

  • The timer is like a built-in function. That variable updateIntervalMillis is the time between updates, which is used when describing the variable weather. I think that everytime weather.update() executes, it checks if it has been 30 seconds from the previous update. If it returns true, it updates, but if false, it just doesn't do anything. But because I put the weather.update() in setup(), it will only update once. I will make a button for refresh later in draw().

  • This post is a redundant fork from:
    http://forum.processing.org/two/discussion/6060/function-doesnt-return-a-string/

    I've posted an example there which uses a separate thread("") which only checks the weather each INTERVAL!

Sign In or Register to comment.