Solution: How to check for internet-connection in Processing

Hi!
I was trying to figure out how to check if a device is connected to the internet, but couldn’t find any helpful results on google (this is the only thing I found). I eventually figured it out, and wanted to share my code, so that other beginners like me won’t have to google for hours. I’ve seen other people post stuff like this, so I hope this is not considered as a waste of space or anything.

boolean isConnected() {
  String[] file; //creates a String that will be loaded with stuff from the internet
  try {
    //load a text file from somewhere on the internet
    file = loadStrings("YourURLWithAFileExtensionLike.txtAtTheEnd");
    //TRY to print it --> throws NullPointerException if it was not loaded correctly
    println(file[0]); 
  } 
  catch (NullPointerException e) { //if there is an exception, do this:
    println("Connection is not available...");
    return false; //function returns false --> not connected
  }
  return true; //function returns true --> connected; I can put this here,
               //because the "return" earlier immediately exits the function,
               //so that this will never be called, unless there is a connection
}
2 Likes

Can’t you simply check for null rather than try/catch it? :thinking:

boolean isConnected() {
  return loadStrings("SomeURL.txt") != null;
}
2 Likes

Um, maybe… :sweat_smile:
The way I tried checking for null before resulted in a crash, and I thought this was the only solution. Anyways, now there is an even shorter solution online, so thank you! :stuck_out_tongue:

1 Like

This is taking advantage of the way that loadStrings already handles URLs – or files, for that matter, anything that is / is not available:

If the file is not available or an error occurs, null will be returned and an error message will be printed to the console. https://processing.org/reference/loadStrings_.html

Note however that this isn’t exactly the same as checking for an internet connection. Depending on your network / configuration, there might be a long delay for a timeout on a loadStrings url request.

2 Likes