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

share|improve this question
2  
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? – muddyfish 2 days ago
3  
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 2 days ago
4  
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 2 days ago
5  
Commodore Basic: PRINT "0" – Mark yesterday
3  
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 yesterday

25 Answers 25

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 http://serverfault.com/a/778830), avoiding any cache issues.

share|improve this answer
    
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 yesterday
    
@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 yesterday
    
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 yesterday
1  
>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 yesterday
2  
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 yesterday

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:~$ 
share|improve this answer
2  
Use a domain like to. rather than 8.8.8.8, to save quite a lot. – Muzer 2 days ago
    
@Muzer yes - thanks – Digital Trauma 2 days ago
2  
@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 2 days ago
2  
@Muzer OK, to sometimes works and sometimes not. I guess some caching going on. I'll use to. just for safety. – Digital Trauma 2 days ago
2  
Why is that a valid domain? – Kos yesterday

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.

share|improve this answer
1  
Always a +1 for 05AB1E answers – WorseDoughnut 2 days ago
    
@WorseDoughnut And why is that? – mbomb007 2 days ago
3  
@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 yesterday
1  
@WorseDoughnut There's already a hyperlink in the answer. – mbomb007 yesterday
    
Can't you connect to to. to save a byte? – ev3commander yesterday

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
share|improve this answer
    
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 2 days ago
    
@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 2 days ago
1  
would this work with ftp instead of http - save another byte? – Floris yesterday
1  
@Floris Nice to see you also here! Unfortunately ftp doesn's seem to work for that site – Luis Mendo yesterday
1  
Hello @LuisMendo yes I sometimes prowl other sites... too bad the ftp doesn't work! – Floris yesterday

Bash 66 62 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.

share|improve this answer
    
I think you can use a shorter URL than google.com, which would allow you to shorten the code. Something like g.gl. – Alex L. 2 days ago
3  
You should also be able to just echo $? instead of that whole if statement. – SomethingDark 2 days ago
3  
you missed "some" ; in the golfed line. – Ipor Sircer yesterday
    
@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 yesterday
    
@AbelTom - it could be argued that 0 is truthy and non-0 is falsey. – SomethingDark yesterday

Perl, 15 bytes

print`curl to.`

Run with:

perl -e 'print`curl 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.

share|improve this answer
    
Couldn't you switch to bash and remove the print? – BlueRaja - Danny Pflughoeft 2 days ago
1  
@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 2 days ago

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.

share|improve this answer

Batch, 8 bytes

ping to.

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

share|improve this answer

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.

share|improve this answer
1  
TOS means top of stack. i think you mean it just leaves data on the stack. – Roman Gräf yesterday
    
That's right. I improved my explanation. Thanks. – Chaos Manor yesterday
    
@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 yesterday

R, 20 bytes

curl::has_internet()

There's a function for exactly this task in the curl package.

share|improve this answer
1  
+1 nice find. For those curious like me, this function is implemented as: function() !is.null(nslookup("r-project.org", error = FALSE)) – plannapus yesterday

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.

share|improve this answer

Bash, 39 bytes

exec 4<>/dev/tcp/to./80&&echo 1||echo 0
share|improve this answer
1  
! exec 4<>/dev/tcp/to./80;echo $? – Jasen yesterday
    
or if you don't need to print true/false but can just return it,exec 4<>/dev/tcp/to./80 – Jasen yesterday

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

share|improve this answer
    
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 yesterday
    
@DJMcMayhem How's your cache? – Ismael Miguel yesterday
    
@DJMcMayhem I tested in Chrome, Win10. Disabled cache from the network tab and checked Offline to test offline/online – Eric Zanchi yesterday
    
This can be a full program in 52 bytes: fetch('://to.').then(a=>alert(1)).catch(a=>alert(0)) – Patrick Roberts yesterday

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
share|improve this answer
2  
This answer implies that this won't always return false when not connected to the internet – muddyfish 2 days ago
    
You can save a byte by adding a parameter to the lambda, like so: f=a=> – XavCo7 2 days ago
1  
Although your answer still seems to be invalid, you can get rid of f=. – Mama Fun Roll 2 days ago
1  
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 yesterday

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.

share|improve this answer

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.

share|improve this answer
    
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 yesterday
1  
@Kos "I don't know" is not truthy/falsey – Restioson 8 hours ago

Powershell, 64 26 23 bytes

Saved 38 bytes, thanks to Shawn Esterman

Saved 3 bytes, and repaired script, thanks to briantist

Test-Connection -q g.gl
share|improve this answer
    
Test-Connection -Quiet to. – Shawn Esterman 2 days ago
    
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 yesterday

Java, 72 bytes

a->new java.net.InetSocketAddress("to.",80).getAddress().isReachable(9);
share|improve this answer
2  
You need to specify the fully qualified name java.net.InetSocketAddress – Snowman yesterday

PHP, 23 PHP + Curl, 14

Using PHP's backtick operator:

<?=`curl to.`;

Orignal answer:

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
share|improve this answer
3  
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). – ais523 2 days ago

Elixir, 33 bytes

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

0 if connected, 1 otherwise.

share|improve this answer

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.

share|improve this answer
    
I think from urllib import* could save a char (and drop l. of course). – Nick T yesterday
    
@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 yesterday

Julia, 10 bytes

run(`dig`)

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

share|improve this answer

PowerShell, 12 bytes

!!(irm g.gl)
share|improve this answer

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.

share|improve this answer
1  
Note that, by default, REPL snippets are not allowed. Put & afterwards to make it into an unnamed function. – LegionMammal978 yesterday
    
Can you point me to a link? – Kelly Lowder yesterday
    

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.