55
\$\begingroup\$

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

\$\endgroup\$
21
  • 5
    \$\begingroup\$ 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? \$\endgroup\$
    – Blue
    Commented Jan 13, 2017 at 13:34
  • 5
    \$\begingroup\$ 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 \$\endgroup\$
    – Luis Mendo
    Commented Jan 13, 2017 at 14:04
  • 5
    \$\begingroup\$ 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). \$\endgroup\$ Commented Jan 13, 2017 at 14:28
  • 12
    \$\begingroup\$ Commodore Basic: PRINT "0" \$\endgroup\$
    – Mark
    Commented Jan 13, 2017 at 19:24
  • 3
    \$\begingroup\$ 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" :) \$\endgroup\$
    – zeppelin
    Commented Jan 13, 2017 at 19:55

32 Answers 32

33
\$\begingroup\$

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.

\$\endgroup\$
11
  • \$\begingroup\$ 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. \$\endgroup\$
    – Titus
    Commented Jan 13, 2017 at 21:04
  • \$\begingroup\$ @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. \$\endgroup\$
    – zeppelin
    Commented Jan 13, 2017 at 21:06
  • \$\begingroup\$ Your solution depends on a non-default install; I woukld consider that exploiting a loophole. You can still win with the two additional bytes. \$\endgroup\$
    – Titus
    Commented Jan 13, 2017 at 21:09
  • 1
    \$\begingroup\$ >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). \$\endgroup\$
    – zeppelin
    Commented Jan 13, 2017 at 21:15
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – Jasen
    Commented Jan 14, 2017 at 0:06
19
\$\begingroup\$

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:~$ 
\$\endgroup\$
8
  • 2
    \$\begingroup\$ Use a domain like to. rather than 8.8.8.8, to save quite a lot. \$\endgroup\$
    – Muzer
    Commented Jan 13, 2017 at 15:57
  • \$\begingroup\$ @Muzer yes - thanks \$\endgroup\$ Commented Jan 13, 2017 at 16:01
  • 2
    \$\begingroup\$ @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) \$\endgroup\$ Commented Jan 13, 2017 at 17:03
  • 2
    \$\begingroup\$ @Muzer OK, to sometimes works and sometimes not. I guess some caching going on. I'll use to. just for safety. \$\endgroup\$ Commented Jan 13, 2017 at 17:13
  • 6
    \$\begingroup\$ Why is that a valid domain? \$\endgroup\$
    – Kos
    Commented Jan 14, 2017 at 6:52
9
\$\begingroup\$

Batch, 8 bytes

ping to.

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

\$\endgroup\$
8
\$\begingroup\$

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.

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Always a +1 for 05AB1E answers \$\endgroup\$ Commented Jan 13, 2017 at 16:06
  • \$\begingroup\$ @WorseDoughnut And why is that? \$\endgroup\$
    – mbomb007
    Commented Jan 13, 2017 at 16:46
  • 4
    \$\begingroup\$ @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. \$\endgroup\$ Commented Jan 13, 2017 at 19:07
  • 1
    \$\begingroup\$ @WorseDoughnut There's already a hyperlink in the answer. \$\endgroup\$
    – mbomb007
    Commented Jan 13, 2017 at 19:08
  • \$\begingroup\$ Can't you connect to to. to save a byte? \$\endgroup\$
    – user46167
    Commented Jan 14, 2017 at 0:05
8
\$\begingroup\$

R, 20 bytes

curl::has_internet()

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

\$\endgroup\$
3
  • 1
    \$\begingroup\$ +1 nice find. For those curious like me, this function is implemented as: function() !is.null(nslookup("r-project.org", error = FALSE)) \$\endgroup\$
    – plannapus
    Commented Jan 14, 2017 at 16:15
  • \$\begingroup\$ Equivalent count: httr::url_ok('g.gl') (albeit deprecated). \$\endgroup\$ Commented Jan 16, 2017 at 1:17
  • 1
    \$\begingroup\$ @JonathanCarroll if you used 'to.' in that it would be one byte less :) \$\endgroup\$
    – Seth
    Commented Apr 4, 2022 at 21:45
6
\$\begingroup\$

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.

\$\endgroup\$
10
  • \$\begingroup\$ I think you can use a shorter URL than google.com, which would allow you to shorten the code. Something like g.gl. \$\endgroup\$
    – hyperneutrino
    Commented Jan 13, 2017 at 15:20
  • 3
    \$\begingroup\$ You should also be able to just echo $? instead of that whole if statement. \$\endgroup\$ Commented Jan 13, 2017 at 16:25
  • 5
    \$\begingroup\$ you missed "some" ; in the golfed line. \$\endgroup\$ Commented Jan 14, 2017 at 1:57
  • \$\begingroup\$ @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. \$\endgroup\$
    – Abel Tom
    Commented Jan 14, 2017 at 3:12
  • \$\begingroup\$ @AbelTom - it could be argued that 0 is truthy and non-0 is falsey. \$\endgroup\$ Commented Jan 14, 2017 at 3:13
6
\$\begingroup\$

Java, 72 bytes

a->new java.net.InetSocketAddress("to.",80).getAddress().isReachable(9);
\$\endgroup\$
0
5
\$\begingroup\$

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
                
\$\endgroup\$
5
  • \$\begingroup\$ 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... :) \$\endgroup\$ Commented Jan 13, 2017 at 14:41
  • \$\begingroup\$ @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 \$\endgroup\$
    – Luis Mendo
    Commented Jan 13, 2017 at 14:44
  • 1
    \$\begingroup\$ would this work with ftp instead of http - save another byte? \$\endgroup\$
    – Floris
    Commented Jan 13, 2017 at 20:02
  • 1
    \$\begingroup\$ @Floris Nice to see you also here! Unfortunately ftp doesn's seem to work for that site \$\endgroup\$
    – Luis Mendo
    Commented Jan 14, 2017 at 0:25
  • 1
    \$\begingroup\$ Hello @LuisMendo yes I sometimes prowl other sites... too bad the ftp doesn't work! \$\endgroup\$
    – Floris
    Commented Jan 14, 2017 at 1:00
4
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Couldn't you switch to bash and remove the print? \$\endgroup\$ Commented Jan 13, 2017 at 17:20
  • 1
    \$\begingroup\$ @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)). \$\endgroup\$
    – Dada
    Commented Jan 13, 2017 at 17:27
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ TOS means top of stack. i think you mean it just leaves data on the stack. \$\endgroup\$ Commented Jan 13, 2017 at 20:17
  • \$\begingroup\$ That's right. I improved my explanation. Thanks. \$\endgroup\$ Commented Jan 13, 2017 at 20:26
  • \$\begingroup\$ @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 '/' \$\endgroup\$ Commented Jan 14, 2017 at 8:09
4
\$\begingroup\$

Javascript, 16 bytes

navigator.onLine

Returns true or false.

Try It!

I'm new here, so IDK if I counted bytes properly, or if builtins are cheating...

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Hi! Welcome to CGCC! I suggest adding a place where we can try this online (usually, we link Try It Online!, but feel free to link anywhere else). \$\endgroup\$
    – lyxal
    Commented Mar 29, 2020 at 0:21
  • \$\begingroup\$ Bytes have been counted correctly. Also, builtins are not cheating unless the challenge disallowed it (which it does not). \$\endgroup\$ Commented Jun 27, 2023 at 19:00
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

Bash, 39 bytes

exec 4<>/dev/tcp/to./80&&echo 1||echo 0
\$\endgroup\$
2
  • 1
    \$\begingroup\$ ! exec 4<>/dev/tcp/to./80;echo $? \$\endgroup\$
    – Jasen
    Commented Jan 14, 2017 at 0:15
  • \$\begingroup\$ or if you don't need to print true/false but can just return it,exec 4<>/dev/tcp/to./80 \$\endgroup\$
    – Jasen
    Commented Jan 14, 2017 at 0:15
3
\$\begingroup\$

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.

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Note that, by default, REPL snippets are not allowed. Put & afterwards to make it into an unnamed function. \$\endgroup\$ Commented Jan 13, 2017 at 22:21
  • \$\begingroup\$ Can you point me to a link? \$\endgroup\$ Commented Jan 13, 2017 at 22:45
  • \$\begingroup\$ See Default for Code Golf: Program, Function or Snippet?. \$\endgroup\$ Commented Jan 13, 2017 at 23:29
  • 1
    \$\begingroup\$ 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! \$\endgroup\$
    – Restioson
    Commented Jan 16, 2017 at 10:44
  • \$\begingroup\$ @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. \$\endgroup\$ Commented Jan 17, 2017 at 15:38
3
\$\begingroup\$

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

\$\endgroup\$
5
  • \$\begingroup\$ 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 \$\endgroup\$
    – DJMcMayhem
    Commented Jan 13, 2017 at 19:02
  • \$\begingroup\$ @DJMcMayhem How's your cache? \$\endgroup\$ Commented Jan 13, 2017 at 19:30
  • \$\begingroup\$ @DJMcMayhem I tested in Chrome, Win10. Disabled cache from the network tab and checked Offline to test offline/online \$\endgroup\$ Commented Jan 13, 2017 at 20:07
  • \$\begingroup\$ This can be a full program in 52 bytes: fetch('://to.').then(a=>alert(1)).catch(a=>alert(0)) \$\endgroup\$ Commented Jan 13, 2017 at 20:30
  • \$\begingroup\$ Doesn't navigator.onLine work? \$\endgroup\$
    – rydwolf
    Commented Mar 29, 2020 at 19:31
2
\$\begingroup\$

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
\$\endgroup\$
4
  • 2
    \$\begingroup\$ This answer implies that this won't always return false when not connected to the internet \$\endgroup\$
    – Blue
    Commented Jan 13, 2017 at 14:57
  • \$\begingroup\$ You can save a byte by adding a parameter to the lambda, like so: f=a=> \$\endgroup\$
    – user62802
    Commented Jan 13, 2017 at 15:05
  • 1
    \$\begingroup\$ Although your answer still seems to be invalid, you can get rid of f=. \$\endgroup\$ Commented Jan 13, 2017 at 15:13
  • 1
    \$\begingroup\$ 78 bytes: a=>{with(new Image()){src="//placehold.it/1x1";onload=b=>a(1);onerror=c=>a()}}´ (got rid of f=` and used with(){}) \$\endgroup\$ Commented Jan 13, 2017 at 19:27
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ Test-Connection -Quiet to. \$\endgroup\$ Commented Jan 13, 2017 at 15:34
  • \$\begingroup\$ PowerShell can't resolve to., you'd have to use g.gl instead. Additionally you can shorten it to Test-Connection -q g.gl. \$\endgroup\$
    – briantist
    Commented Jan 13, 2017 at 20:49
2
\$\begingroup\$

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
\$\endgroup\$
6
  • 4
    \$\begingroup\$ 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). \$\endgroup\$
    – user62131
    Commented Jan 13, 2017 at 17:51
  • \$\begingroup\$ Does an array count as truthy? I'll allow it to compete anyway though, since it is my question. Just out of interest. \$\endgroup\$
    – Restioson
    Commented Jan 16, 2017 at 10:11
  • \$\begingroup\$ @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. \$\endgroup\$
    – Christoph
    Commented Jan 16, 2017 at 10:30
  • \$\begingroup\$ @Cristoph I don't think "Array" counts as truthy or falsey \$\endgroup\$
    – Restioson
    Commented Jan 16, 2017 at 10:42
  • \$\begingroup\$ @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. \$\endgroup\$
    – Christoph
    Commented Jan 16, 2017 at 11:53
2
\$\begingroup\$

Python 3 + requests, 59 55 53 39 bytes

There has to be a requests answer, right?

from requests import*
get("http://to.")

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)
  • -14 bytes (thanks pppery)
\$\endgroup\$
4
  • \$\begingroup\$ You could shorten this by using a different protocol (ftp, perhaps), and doing except:0/0. \$\endgroup\$
    – user45941
    Commented Jan 25, 2017 at 21:30
  • \$\begingroup\$ @Mego I think requests only does http(s). I've added the 0/0. \$\endgroup\$
    – matsjoyce
    Commented Jan 25, 2017 at 21:56
  • \$\begingroup\$ Why is the try-except statement necessary? \$\endgroup\$ Commented Apr 9, 2020 at 2:06
  • \$\begingroup\$ @pppery Umm, yes. Thanks for pointing it out. I have no idea. Must have been a relic of the original solution. \$\endgroup\$
    – matsjoyce
    Commented Apr 9, 2020 at 10:07
2
\$\begingroup\$

Vyxal, 8 bytes

`g.gl`¨U

Wait, ¨U exists?

Doesn't work on the online interpreter. Exits with error for falsy, runs successfully with no output for truthy.

`g.gl`   # string literal g.gl
      ¨U # GET request to that URL

For fun, here's a fairly cheaty version. Ports JavaScript:

Vyxal E, 13 bytes

`ƈ⌈(₍†.on¬ḣ)`

Try it Online!

Just runs the JavaScript alert(navigator.onLine) using the E flag

\$\endgroup\$
2
1
\$\begingroup\$

Elixir, 33 bytes

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

0 if connected, 1 otherwise.

\$\endgroup\$
1
\$\begingroup\$

PowerShell, 12 bytes

!!(irm g.gl)
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ I think from urllib import* could save a char (and drop l. of course). \$\endgroup\$
    – Nick T
    Commented Jan 13, 2017 at 23:04
  • \$\begingroup\$ @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 \$\endgroup\$
    – Chris H
    Commented Jan 14, 2017 at 8:27
1
\$\begingroup\$

Julia + Bash (with dnsutils), 10 bytes

run(`dig`)

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

\$\endgroup\$
0
1
\$\begingroup\$

Arturo, 21 bytes

download"http://x.gl"

Outputs via exit code.

\$\endgroup\$
1
\$\begingroup\$

R, 18 bytes

(2 bytes shorter than the previous R answer; additionally, this solution does not require an external package to be installed.)

!is.null(nsl("a"))

Try it online!

The nsl function looks up the IP address of a hostname. If there is no Internet connection, it outputs NULL, otherwise it outputs an IP address.

Note that we do not need to specify an existing domain name: when the domain name does not resolve (and as long as it does not end in a .), the domain name is instead appended to the server domain name. So we can use any 1-letter domain name, and the output of nsl is the non-NULL server IP. I think this behaviour is not specific to R.

\$\endgroup\$
1
\$\begingroup\$

Scratch (scratchblocks3 syntax), 32 bytes

define
say(translate(1)to(Zulu v

"1" on success and an empty string on failure. Relies on Google Translate.

(Also, a slightly more amusing solution that actually outputs "true" but was unfortunately not optimal:)

define
say(translate(gwir)to(English v
\$\endgroup\$
2
  • \$\begingroup\$ Wouldn't translating to Lao be shorter, or does Scratch not support it? \$\endgroup\$
    – Restioson
    Commented Apr 5, 2022 at 19:28
  • \$\begingroup\$ @Restioson Scratch doesn't support Lao, for some reason. The shortest language names are Thai and Zulu \$\endgroup\$
    – qarz
    Commented Apr 6, 2022 at 0:29
0
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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