Is there any way to check if the device has internet connection?

How can I check if the device I am currently working on is connected to the internet. Is there any library that I can use?

How do you define “connected to the internet”?

As this question is not easily answerable, I’d just try to open a connection to the desired target. Either you can reach your target or you can’t.

Just lets look back a couple of days, an important node in germany blacked out for 4 hours. Germany was essentially offline for about 2 hours before everything got rerouted.

Still, technically my WiFi-Card was connected to the internet via my fritz-box.

I’d just try to open a connection to the desired target. Either you can reach your target or you can’t.

That’s similar to how reachability libs work on ios, so I guess it’s the most convenient approach.

EDIT Actually, I’m wrong.

From https://developer.apple.com/library/content/samplecode/Reachability/Introduction/Intro.html

[…] it demonstrates how to know when IP can be routed and when traffic will be routed through a Wireless Wide Area Network (WWAN) interface such as EDGE or 3G. Note: Reachability cannot tell your application if you can connect to a particular host, only that an interface is available that might allow a connection, and whether that interface is the WWAN.

So, I guess, the libraries on top of it allow for checking the connection status to a particular host …

I’m not sure about iOS development at all, but from what you have quoted, this seems to be more like “If I try to access this host, will it be routed through mobile network or the WiFi?”.

Yeah, I was wrong.

I thought it tried to establish a connection with the remote host for some reason. But it just shows the interface that would be used for this.

Actually the device is always connected. I have to do a simple check like to ping a website so I can know if there is real connection or no.

ping a website

Just ping or assert a 200 http response?

Do you want to ping (ICMP ECHO request) or know if a website is reachable? One can easily work without the other for the same target host.

Therefore my suggestion remains, just do the request and handle errors (or let it crash).

This is what I needed. It is okay to use for test purposes.

defp net_status() do                                                                                                                       
  case HTTPoison.head("www.google.com") do                                                                                                 
    {:ok, _} -> Logger.debug("Internet connection: OK")                                                                                    
    {:error, _} -> Logger.error("No internet connection!")                                                                                 
  end                                                                                                                                      
end
1 Like