Check if Internet connexion is working

Hi guys, I just have a simple question. It’s just I am just really bad at network. How can I check with Crystal if there is any network before I start an http client request? Because I need to print an error if there is no network

1 Like

My understanding is the only way to know if you can connect to a server is to try and do so. So maybe the easiest/best way would be to like make some HEAD request with low timeouts and see if it errors or not.

1 Like

There are ways you can tell if you’re connected to a network (in browsers, there’s a navigator.onLine property, so whatever strategy they use to determine that could theoretically also be used in Crystal), but there is no guarantee that that network is connected to anything else. It just tells you that you have a non-loopback IP address. So you can have a network connection, but not an internet connection.

Examples where this is important:

  • airplane wifi
  • edge networks, such as power stations in remote locations
  • conference wifi, especially if you’re the one presenting :upside_down_face:
  • ISP outages

So I agree with @Blacksmoke16, but I wouldn’t make a full HTTP request since that is more than you need. You can likely get away with simply making a TCP connection:

require "socket"

begin"", port: 80, connect_timeout: 500.milliseconds).close
rescue ex : IO::Error
  # no internet connectivity

I chose Google here because resolves to different IP addresses depending on where you are — you can ping that domain from Iowa, USA or Sydney, Australia and get similar latencies. With a few notable exceptions, you’re unlikely to be more than 100ms latency from a Google point of presence. But you can choose any host (even a raw IP address to skip DNS resolution) that you know is going to be relatively close and tune the 500.milliseconds to whatever your tolerance for network latency is.


Oh thank you so much, perfect !