# Check if computer is connected to the internet

Write a program which, according to whether the script has access to the internet, produces an output which is "Truthy/Falsey". You may try and connect to any existing site, at your own discretion (don't use a shady site which only has 10% uptime - try to keep to above 80% annual uptime). If the site is down, your program does not have to work.

It must be a standalone program or a function. You may use libraries outside of the standard library to achieve this. Standard loopholes are forbidden. This is code golf, so the code with the shortest byte-count wins.

Example pseudocode:

function a:
try:
connect to internet
return 1
catch error:
return 0


This is my first post on code golf, so if this violates any rules in any way or is a dupe, please alert me.

EDIT: Due to numerous suggestions, I have removed the UTF-8 byte count restriction

• Instead of true and false, I recommend allowing any of our defaults for truthy and falsiness. Also, by internet, do you mean the network outside your local network? Do programs still have to work if say google is down or any other large site? – Blue Jan 13 '17 at 13:34
• Byte count is usually done in the language's native or most convenient encoding, which is not always UTF-8. Unless you a have a good reason to enforce UTF-8, I think the encoding should be left at the programmer's choice – Luis Mendo Jan 13 '17 at 14:04
• I see almost everyone is using g.gl / http://g.gl/, but to. / http://to./ seems to be one byte shorter (not all languages see it as a valid url through). – Kevin Cruijssen Jan 13 '17 at 14:28
• Commodore Basic: PRINT "0" – Mark Jan 13 '17 at 19:24
• The very machine I'm typing this at, is technically a part of the "Internet", as it can be accessed from the outside (via NAT and port forwarding). So, if you think of it, the "internet detection" script can probably be reduced to "true" :) – zeppelin Jan 13 '17 at 19:55

# 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 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.

• Quote from man dig: Unless it is told to query a specific name server, dig will try each of the servers listed in /etc/resolv.conf. If no usable server addresses are found, dig will send the query to the local host. – Titus Jan 13 '17 at 21:04
• @Titus, yep that is correct, see "disclaimer" part of my answer, but as long as your DNS server (as specified in your resolv.conf) is on your provider's side, it works just nice. – zeppelin Jan 13 '17 at 21:06
• Your solution depends on a non-default install; I woukld consider that exploiting a loophole. You can still win with the two additional bytes. – Titus Jan 13 '17 at 21:09
• >Your solution depends on a non-default install Nope, it is exactly how it works on my machine (and that is already enough according to Meta). Moreover, using your provider's DNS server, is a pretty common setup indeed (and it will normally be in your resolv.conf too). – zeppelin Jan 13 '17 at 21:15
• defualt settigns depends on what settings you used at install time if you configured the network using DHCP then resolv.conf probably points at your router. if you configured networking manually it will have whatever DNS server you nominated. – Jasen Jan 14 '17 at 0:06

# 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:~$

• Use a domain like to. rather than 8.8.8.8, to save quite a lot. – Muzer Jan 13 '17 at 15:57
• @Muzer yes - thanks – Digital Trauma Jan 13 '17 at 16:01
• @Muzer unless there is a local to that the resolver is configured to find, it will still go to the right one (and maybe being able to ping a local to is enough of being connected to the internet) – Christian Sievers Jan 13 '17 at 17:03
• @Muzer OK, to sometimes works and sometimes not. I guess some caching going on. I'll use to. just for safety. – Digital Trauma Jan 13 '17 at 17:13
• Why is that a valid domain? – Kos Jan 14 '17 at 6:52

## Batch, 8 bytes

ping to.


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

# 05AB1E, 11 9 bytes

Saved 2 bytes on "to." courtesy of ev3commander

…to..wgX›


Checks if the length of the content at http://to. is greater than 1.
.w returns 0 on error.

• Always a +1 for 05AB1E answers – WorseDoughnut Jan 13 '17 at 16:06
• @WorseDoughnut And why is that? – mbomb007 Jan 13 '17 at 16:46
• @mbomb007 Just been a huge fan of the language since Adnan starting working on it and posting it here; it's definitely a fascinating language to delve into. – WorseDoughnut Jan 13 '17 at 19:07
• Can't you connect to to. to save a byte? – ev3commander Jan 14 '17 at 0:05

# MATL, 15 14 bytes

One byte saved thanks to Kevin Cruijssen's suggestion

'http://to.'Xi


Output is through STDOUT. This displays a non-empty string containing non-zero chars (which is truthy) if there is an Internet connection; and displays nothing (which is falsy) if there's no connection.

This can't be tested online because the Xi is not allowed in the online interpreters.

### Explanation

'http://to.'  % Push this string
Xi            % Return contents of that URL as a string. If there is no Internet
% connection this gives an error, with no output on STDOUT

• Would you consider urlread('http://g.gl') to be an OK answer by itself? It will error and leave the workspace empty if the connection is down. It will display an error message, but technically that's to STDERR...? I thought it was a bit of a stretch, so I did it this way. But skipping try seems to give the same result as your code, or? You leave the stack empty too don't you? Nice answer by the way... :) – Stewie Griffin Jan 13 '17 at 14:41
• @StewieGriffin Thanks! Yes, I think urlread('http://g.gl') is valid (and is the same as my code does), as STDERR is ignored by default, and an empty STDOUT is falsy in MATLAB – Luis Mendo Jan 13 '17 at 14:44
• would this work with ftp instead of http - save another byte? – Floris Jan 13 '17 at 20:02
• @Floris Nice to see you also here! Unfortunately ftp doesn's seem to work for that site – Luis Mendo Jan 14 '17 at 0:25
• Hello @LuisMendo yes I sometimes prowl other sites... too bad the ftp doesn't work! – Floris Jan 14 '17 at 1:00

## Bash 6662 21 bytes

ping -c1 g.gl echo $?  Thanks @Alex L. for the URL shortening tip. Ungolfed version: r=$(ping -c1 g.gl)
if [ $? -ne 0 ]; then echo "0" else echo "1" fi  This is my first answer in Bash , i'm not sure i have shortened the script enough. • I think you can use a shorter URL than google.com, which would allow you to shorten the code. Something like g.gl. – HyperNeutrino Jan 13 '17 at 15:20 • You should also be able to just echo$? instead of that whole if statement. – SomethingDark Jan 13 '17 at 16:25
• you missed "some" ; in the golfed line. – Ipor Sircer Jan 14 '17 at 1:57
• @IporSircer Thanks. :) @SomethingDark Hello, echo $? prints a 0 if success, or else it returns a 2 in this case. I have not looked into source code of the implementation of ping but i am assuming, there are different return codes depending on the stuation. Hence, i used if else strategy. – Abel Tom Jan 14 '17 at 3:12 • @AbelTom - it could be argued that 0 is truthy and non-0 is falsey. – SomethingDark Jan 14 '17 at 3:13 ## R, 20 bytes curl::has_internet()  There's a function for exactly this task in the curl package. • +1 nice find. For those curious like me, this function is implemented as: function() !is.null(nslookup("r-project.org", error = FALSE)) – plannapus Jan 14 '17 at 16:15 • Equivalent count: httr::url_ok('g.gl') (albeit deprecated). – Jonathan Carroll Jan 16 '17 at 1:17 # Java, 72 bytes a->new java.net.InetSocketAddress("to.",80).getAddress().isReachable(9);  • You need to specify the fully qualified name java.net.InetSocketAddress – user18932 Jan 13 '17 at 20:11 ## Perl, 15 bytes printcurl to.  Run with: perl -e 'printcurl to.' 2> /dev/null  curl outputs stuffs on STDERR, don't mind them. If the computer has access to internet, it will print a few lines of html (truthy), otherwise, it will print nothing (falsy). Saved 1 bytes by using to. (instead of my previous b.io) thanks to @Kevin Cruijssen. • Couldn't you switch to bash and remove the print? – BlueRaja - Danny Pflughoeft Jan 13 '17 at 17:20 • @BlueRaja-DannyPflughoeft Yup, that would work (there is already a answer in bash though (they use wget instead of curl but it's the same thing)). – Dada Jan 13 '17 at 17:27 ## C#, 87 bytes _=>{try{new System.Net.WebClient().OpenRead("http://g.gl");return 1;}catch{return 0;}};  If an exception is considered falsey, which I don't think it is, then this is 65 bytes: _=>new System.Net.WebClient().OpenRead("http://g.gl").ReadByte();  I also tried using the link http://to. as stated by @KevinCruijssen but it didn't seem to work. # 8th, 23 21 bytes Two bytes saved thanks to Kevin Cruijssen's suggestion and to my discovery: http://to seems to work as well as http://to. (saving another byte) "http://to" net:get .  If site http://to can be reached, it then prints true. Otherwise it prints false. It leaves retrieved data on the stack. • TOS means top of stack. i think you mean it just leaves data on the stack. – Roman Gräf Jan 13 '17 at 20:17 • That's right. I improved my explanation. Thanks. – Chaos Manor Jan 13 '17 at 20:26 • @ev3commander Have you tried with http://to ? It works in my case (I see an Apache2 Ubuntu Default Page). It seems that there is no need to append '.' or '/' – Chaos Manor Jan 14 '17 at 8:09 # MATLAB, 32 22 bytes urlread('http://g.gl')  Explanation: If the internet connection is up, this will result in ans (the default variable) being a string with the entire html-code in plain text (which is true in MATLAB). If the internet connection is down, this will write an error message to STDERR and leave the workspace empty (which is false in MATLAB). Unfortunately, urlread requires a full url-address, so g.gl is not enough. 11 of the 22 bytes are therefore just the url-address. Alternative approach: A solution that catches the error and leave a 0 (also false) in the workspace if the connection is down: 0;try urlread('http://g.gl'),end  0; initializes the default variable ans to 0, which is false in MATLAB. Then we try to read the url. This will give an error if the internet connection is down, or a character array if not (which is true in MATLAB). We don't need to catch anything, so we just end. If the urlread call was successful, then ans will be a long string with the content of the website, otherwise ans=0. ## Bash, 39 bytes exec 4<>/dev/tcp/to./80&&echo 1||echo 0  • ! exec 4<>/dev/tcp/to./80;echo$? – Jasen Jan 14 '17 at 0:15
• or if you don't need to print true/false but can just return it,exec 4<>/dev/tcp/to./80 – Jasen Jan 14 '17 at 0:15

# JavaScript ES6, 71 43 bytes

fetch.then(a=>alert(1)).catch(a=>alert)


Alerts 1 if online, alerts an empty string if offline. Thanks to Patrick Roberts for helping me shave off some bytes

Old version

_=>fetch('http://enable-cors.org').then(a=>alert(a)).catch(a=>alert(0))


Alerts [object Reponse] if online, alerts 0 if offline

Removed the code snippet, it doesn't work because it loads from a different domain without CORS, but it works in the browser console

• Hmm. This correctly prints "true" when I'm connected, but it doesn't print anything if I disconnect and run it in my browser. What browser/OS did you test this in? I'm using chrome-win7 – DJMcMayhem Jan 13 '17 at 19:02
• @DJMcMayhem How's your cache? – Ismael Miguel Jan 13 '17 at 19:30
• @DJMcMayhem I tested in Chrome, Win10. Disabled cache from the network tab and checked Offline to test offline/online – Zanchi Jan 13 '17 at 20:07
• This can be a full program in 52 bytes: fetch('://to.').then(a=>alert(1)).catch(a=>alert(0)) – Patrick Roberts Jan 13 '17 at 20:30

# JavaScript ES6, 90 81 Bytes

f=a=>{i=new Image();i.src="//placehold.it/1x1";i.onload=b=>a(1);i.onerror=c=>a()}


# JavaScript ES6, 22 21 bytes (Invalid)

Some browsers don't fully support, or produce the expected result when using navigator.onLine.

f=a=>navigator.onLine

• This answer implies that this won't always return false when not connected to the internet – Blue Jan 13 '17 at 14:57
• You can save a byte by adding a parameter to the lambda, like so: f=a=> – XavCo7 Jan 13 '17 at 15:05
• Although your answer still seems to be invalid, you can get rid of f=. – Mama Fun Roll Jan 13 '17 at 15:13
• 78 bytes: a=>{with(new Image()){src="//placehold.it/1x1";onload=b=>a(1);onerror=c=>a()}}´ (got rid of f= and used with(){}) – Ismael Miguel Jan 13 '17 at 19:27

# Scala, 54 bytes

x=>(Runtime.getRuntime exec "ping -c 1 ai."waitFor)<1


Pretty simple; executes a ping command to http://ai./, and returns true if it exits with 0, or false otherwise.

# Brainfuck (non-competing) 21 bytes

++++++[>++++++++<-]>.


Brainfuck can't connect to the internet (as far as I'm aware), so since the program is unable to connect, the answer is always 0

Non-competing because it seems to fall under the hard-coded output standard loophole, even though this program technically is correct for the challenge.

• Brainfuck can't connect, but the computer I'm running this on can still be connected to the internet (or not). A proper brainfuck solution is a program that always responds "I don't know" – Kos Jan 14 '17 at 6:54
• @Kos "I don't know" is not truthy/falsey – Restioson Jan 15 '17 at 9:42
• It isn't "I don't know", it is "I can't therefore the answer is no" – Cody Jan 17 '17 at 16:36
• maybe just print the byte '\0' since this is also 0. you would have a code of only 1 byte – 12431234123412341234123 Feb 18 '17 at 7:14

## Powershell, 6426 23 bytes

Saved 38 bytes, thanks to Shawn Esterman

Saved 3 bytes, and repaired script, thanks to briantist

Test-Connection -q g.gl

• Test-Connection -Quiet to. – Shawn Esterman Jan 13 '17 at 15:34
• PowerShell can't resolve to., you'd have to use g.gl instead. Additionally you can shorten it to Test-Connection -q g.gl. – briantist Jan 13 '17 at 20:49

# PHP, 23 PHP + Curl, 14

Using PHP's backtick operator:

<?=curl to.;


I will try to make a start:

<?=file('http://x.gl');


This outputs nothing if x.gl can't be reached and Array if it is.

Another version where I'm not quite sure if they fit:

<?=getmxrr('x.gl',$a); // 22 chars  • Re "is that a loophole", I think the normal consensus is that it counts as a language dialect (so the answer is PHP + Curl, 15 bytes). – user62131 Jan 13 '17 at 17:51 • Does an array count as truthy? I'll allow it to compete anyway though, since it is my question. Just out of interest. – Restioson Jan 16 '17 at 10:11 • @Restioson php converts an array to the string "Array" when you try to print it (<?=) and boolean false will be converted to "". So the actual return value is not an array but a non empty string or an empty string. – Christoph Jan 16 '17 at 10:30 • @Cristoph I don't think "Array" counts as truthy or falsey – Restioson Jan 16 '17 at 10:42 • @Restioson It's a string that implicitly converts to boolean true. A branch if ("Array") echo 'thruthy'; would be taken therefore it's truthy. The empty string wouldn't take the branch and is therefore falsey. – Christoph Jan 16 '17 at 11:53 # Python 3 + requests, 5955 53 bytes There has to be a requests answer, right? from requests import* try:get("http://to.") except:Z  Exit status is 0 for internet, 1 for no internet. Example: $ python inet.py
$echo$?
0
$# Remove ethernet cable$ python inet.py
$echo$?
1


Changelog:

• -4 bytes (thanks Mego)
• You could shorten this by using a different protocol (ftp, perhaps), and doing except:0/0. – Mego Jan 25 '17 at 21:30
• @Mego I think requests only does http(s). I've added the 0/0. – matsjoyce Jan 25 '17 at 21:56

# Elixir, 33 bytes

{:ok,_}=:inet.getaddr('to',:inet)


0 if connected, 1 otherwise.

# PowerShell, 12 bytes

!!(irm g.gl)


## Mathematica 10 Bytes

Assuming you have a valid copy of Mathematica, and login credentials on user.wolfram.com

CloudPut@1


will write the value 1 to the cloud. Truthy: CloudObject[""] Falsey: $Failed CloudGet@%  Will return the value 1 that was uploaded to the cloud. • Note that, by default, REPL snippets are not allowed. Put & afterwards to make it into an unnamed function. – LegionMammal978 Jan 13 '17 at 22:21 • Can you point me to a link? – Kelly Lowder Jan 13 '17 at 22:45 • – LegionMammal978 Jan 13 '17 at 23:29 • In my opinion, this is the best answer here. But does Cloud object count as truthy? I would say that the 1 in the cloud is truthy, though. Nice answer! – Restioson Jan 16 '17 at 10:44 • @LegionMammal978, I can put the code, as is, in a .wl package file and run it as a "program" as allowable per the original question. Ordinarily these sorts of questions call for a function with inputs; no user input is necessary. Furthermore, testing of my truthy/false as a function works just as well with or without the &. In CloudPut@1&===$Failed the & makes absolutely no difference. Lastly, the program both returns and prints the output, so it is not in fact a REPL snippet as you suggest. – Kelly Lowder Jan 17 '17 at 15:38

## Python 2.7, 70 77 Bytes

from urllib import*
a=1
try:urlopen('http://to.')
except:a=0
print a


import urllib as l
try:
l.urlopen('http://a.uk')
print 1
except:
print 0


Uses 1 for truthy, 0 for falsy. a.uk redirects to a motorbike clothing company. Saved 3 bytes by assigning to a variable and printing that. And another one for the "to." trick (confirmed to work with urllib), two for getting rid of the pesky indents.

• I think from urllib import* could save a char (and drop l. of course). – Nick T Jan 13 '17 at 23:04
• @NickT I forgot you could drop the space between import and * so I think you're right but I'm on mobile and I'll fix it later – Chris H Jan 14 '17 at 8:27

# Julia + Bash (with dnsutils), 10 bytes

run(dig)


command in julia creates a cmd object that can be run with run.

# Clojure, 49 bytes

#(try(slurp"http://to.")1(catch Exception _ nil))


Returns 1 if it can connect, and nil otherwise.

Just attempts to slurp the page; throwing a NoRouteToHostException exception on failure, which is caught.

Unfortunately, the protocol and dot seem to be mandatory.

# Javascript (Nashorn), 61 bytes

print(new java.net.InetSocketAddress("to.",80).getAddress())
`