Check if computer is connected to the internet

Bash (with dnsutils), 3 bytes

Sends a DNS request for "." (DNS root), exit code is 0 for success and >0 otherwise.

Golfed

dig

Test

% dig >/dev/null; echo $?;        
0

% nmcli nm wifi off
% dig >/dev/null; echo $?;
9

Disclaimer

This will obviously only work if your DNS server is sitting in the provider's network, i.e. in the "Internet" (as your provider network is normally a part of it), or if your system is using a public DNS server (like 8.8.8.8 from Google, which Android based systems use), as otherwise, you can get a cached copy from a local LAN server (or localhost).

But I assume this is not against the code-golf rules, as there are obviously more than one system where this does work as intended.

Pure-HTTP methods can also give false positives, due to an intermediate caching proxy, and are not guaranteed to work everywhere, so that is not something unique to this method.

A slightly more reliable version, 8 bytes

dig +tra

(a little tribute to @Digital Trauma !)

Enables the "trace mode", which will force dig to do the recursive search by itself (see https://serverfault.com/a/778830), avoiding any cache issues.


Bash + GNU utils, 8

  • 5 bytes saved thanks to @Muzer.
wget to.

The other shell answers check the return code and echo some status output accordingly. This is unnecessary. The shell return code is already a usable Truthy/Falsey code and accessible in the $? parameter which is idiomatic for bash. Return code 0 means True. Return code >0 means False.

In use:

ubuntu@ubuntu:~$ wget to.
--2017-01-13 09:10:51--  http://to./
Resolving to. (to.)... 216.74.32.107, 216.74.32.107
Connecting to to. (to.)|216.74.32.107|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 11510 (11K) [text/html]
Saving to: ‘index.html.6’

index.html.6        100%[===================>]  11.24K  --.-KB/s    in 0.04s   

2017-01-13 09:10:51 (285 KB/s) - ‘index.html.6’ saved [11510/11510]

ubuntu@ubuntu:~$ echo $?
0
ubuntu@ubuntu:~$ sudo ifconfig ens33 down
ubuntu@ubuntu:~$ wget to.
--2017-01-13 09:11:00--  http://to./
Resolving to. (to.)... failed: Temporary failure in name resolution.
wget: unable to resolve host address ‘to.’
ubuntu@ubuntu:~$ echo $?
4
ubuntu@ubuntu:~$ sudo ifconfig ens33 up
ubuntu@ubuntu:~$ # Local network up, upstream link down
ubuntu@ubuntu:~$ wget to.
--2017-01-13 09:11:34--  http://to./
Resolving to. (to.)... failed: Name or service not known.
wget: unable to resolve host address ‘to.’
ubuntu@ubuntu:~$ echo $?
4
ubuntu@ubuntu:~$ 

Batch, 8 bytes

ping to.

ping will set ERRORLEVEL to 1 if the address cannot be resolved or reached.