Check if computer is connected to the internet

49

3

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

Restioson

Posted 2017-01-13T13:29:41.013

Reputation: 543

4

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 – 2017-01-13T13:34:07.287

@muddyfish thanks so much for your answer! I will edit my question to be more clear :) – Restioson – 2017-01-13T13:38:37.083

3Byte 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 – 2017-01-13T14:04:23.273

@LuisMendo I chose this to prevent ambiguity – Restioson – 2017-01-13T14:20:41.357

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 – 2017-01-13T14:28:36.790

9Commodore Basic: PRINT "0" – Mark – 2017-01-13T19:24:58.260

3The 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 – 2017-01-13T19:55:05.117

2@Restioson We have a Meta question to define how to count size of programs. Enforcing counting in UTF8 is just going to make things more confusing. Also, what if someone solves this in, say, Vim? Or TI-Basic? How do you count those in UTF8? – Fund Monica's Lawsuit – 2017-01-13T22:18:57.807

1

@KevinCruijssen to (without the . at the end) also seems to work.

– NobodyNada - Reinstate Monica – 2017-01-13T22:26:30.033

What is an objective definition of "80% uptime"? And is that defined to be in the last week, last month, or what? – Buffer Over Read – 2017-01-14T13:15:18.100

Another thing, does the code have to check/ping live internet sites or is checking the DNS server okay? Because the DNS server being operational doesn't technically mean your computer can connect to the WWW, even if it might usually do. – Buffer Over Read – 2017-01-14T13:18:49.333

@H Walters The reason I said "WWW" is because that's how I interpreted the question. If OP meant just the internet, that would be different. – Buffer Over Read – 2017-01-14T21:07:29.453

@TheBitByte true. But I mean do not use a site which is only on on Thursdays, for example. Keep it sensible – Restioson – 2017-01-15T09:28:43.377

@zeppelin your computer would no longer be connected to the internet, if, say, I made your means of network communication break, e.g unplugging your ethernet cable – Restioson – 2017-01-15T09:34:06.807

@TheBitByte yes, checking a DNS server is OK, as long as it isn't on your local network (LAN, hosted by your local router) – Restioson – 2017-01-15T09:35:07.830

It's nice that my question has mainly "mainstream" languages in answers as opposed to the usual horde of esolangs in answers. – Restioson – 2017-01-15T12:53:02.383

@Restioson This is Code Golf SE. I'm not sure what answers you were expecting to get. Anyways, can I just ping the DNS server without having to ping a live WWW website? In other words, technically the ISP's DNS server working isn't always an indication of the WWW working, even if it usually is. – Buffer Over Read – 2017-01-15T21:22:29.057

@Mark ? 0 (or even ?0?) should do it. Untested - from memory. – Thorbjørn Ravn Andersen – 2017-01-16T03:04:05.453

@NobodyNada Hmm.. It doesn't for me, and I tested it on three different devices/networks. :S – Kevin Cruijssen – 2017-01-16T09:16:51.873

@Mark - not really. There is a TCP/IP implementation for Commodore 64, and there even are network cards for C64 with embedded TCP/IP. – Radovan Garabík – 2017-03-01T12:17:08.650

@KevinCruijssen seems http://to. is down now

– Restioson – 2017-07-27T17:18:38.217

Answers

29

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.

zeppelin

Posted 2017-01-13T13:29:41.013

Reputation: 7 884

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 – 2017-01-13T21:04:18.277

@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 – 2017-01-13T21:06:43.597

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 – 2017-01-13T21:09:36.357

1ockquote>

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 – 2017-01-13T21:15:05.940

@Titus there are also lots of systems around which will just use public DNS servers (like 8.8.8.8 from Google), e.g. almost every Android-based system. – zeppelin – 2017-01-13T23:17:07.240

2defualt 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 – 2017-01-14T00:06:09.080

What if you're connected to a LAN with DNS, but not the internet? People who are trying to lookup short web sites on the internet here are going to figure out if they are on the internet versus such LAN's... this solution doesn't seem to be even trying to do that. – H Walters – 2017-01-14T17:29:00.463

@HWalters

What if you're connected to a LAN with DNS, but not the internet?

Then you will (possibly) get a cached response (as described in "Disclaimer").

... figure out if they are on the internet versus such LAN'

Only if they do not have a caching proxy, like Squid, in their LAN (which is a very common setup too), in which case they will just get a cached response every time.

The point is that there is still a (considerable) number of real-world setups, that will work just nice, e.g. most Android devices will just use a public Google DNS.

– zeppelin – 2017-01-14T17:57:36.680

@zeppelin I'm not sure we're on the same wavelength. You're talking about cached entries here (and in your disclaimer). And sure, if the LAN's connected and then disconnected, such creatures might indeed exist. But that's kind of way off to the side of what I'm talking about... live DNS entries on the LAN... entries about the LAN, not generally accessible from the internet. (Maybe WAN gives you a better image). – H Walters – 2017-01-14T18:11:29.160

ockquote>

live DNS entries on the LAN... entries about the LAN, not generally >accessible from the internet (Maybe WAN gives you a better image).

HTTP-based method might as well fail to detect an isolated WLAN (e.g. if there is a proxy server which will return a "dummy" page, explaining that internet access is disabled in response to any "external" URI). (which is pretty normal for a corporate WLAN).

But that is not the point, really, as long as there are at least some real-world setups, the method works for, that is just fine for the purposes of [codegolf]. – zeppelin – 2017-01-14T18:23:40.153

Great answer! Wouldn't have thought an answer so short possible! Well done. – Restioson – 2017-01-15T12:52:08.163

19

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

Digital Trauma

Posted 2017-01-13T13:29:41.013

Reputation: 64 644

2Use a domain like to. rather than 8.8.8.8, to save quite a lot. – Muzer – 2017-01-13T15:57:28.293

@Muzer yes - thanks – Digital Trauma – 2017-01-13T16:01:46.423

Needs to have the dot at the end I'm afraid, otherwise it searches on your local network. – Muzer – 2017-01-13T16:10:43.777

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 – 2017-01-13T17:03:53.367

2@Muzer OK, to sometimes works and sometimes not. I guess some caching going on. I'll use to. just for safety. – Digital Trauma – 2017-01-13T17:13:32.960

4Why is that a valid domain? – Kos – 2017-01-14T06:52:38.207

This doesn't work for me: https://hastebin.com/uviceyomiw.pas, maybe it's a Ubuntu thing?

– 2xsaiko – 2017-02-28T15:58:16.407

@Kos because there's no reason it wouldn't be valid? – user253751 – 2017-05-11T11:51:31.937

9

Batch, 8 bytes

ping to.

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

Neil

Posted 2017-01-13T13:29:41.013

Reputation: 95 035

8

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.

Emigna

Posted 2017-01-13T13:29:41.013

Reputation: 50 798

1Always a +1 for 05AB1E answers – WorseDoughnut – 2017-01-13T16:06:05.237

@WorseDoughnut And why is that? – mbomb007 – 2017-01-13T16:46:33.133

4@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 – 2017-01-13T19:07:54.727

1@WorseDoughnut There's already a hyperlink in the answer. – mbomb007 – 2017-01-13T19:08:22.567

Can't you connect to http://to./ to save a byte?

– ev3commander – 2017-01-14T00:05:15.727

@ev3commander: Apparently I can. Didn't work when i tried yesterday but it does now. Thanks :) – Emigna – 2017-01-14T13:00:20.443

5

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

Luis Mendo

Posted 2017-01-13T13:29:41.013

Reputation: 87 464

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 – 2017-01-13T14:41:15.143

@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 – 2017-01-13T14:44:57.430

1would this work with ftp instead of http - save another byte? – Floris – 2017-01-13T20:02:28.293

1@Floris Nice to see you also here! Unfortunately ftp doesn's seem to work for that site – Luis Mendo – 2017-01-14T00:25:00.593

1Hello @LuisMendo yes I sometimes prowl other sites... too bad the ftp doesn't work! – Floris – 2017-01-14T01:00:25.190

5

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.

Abel Tom

Posted 2017-01-13T13:29:41.013

Reputation: 1 150

I think you can use a shorter URL than google.com, which would allow you to shorten the code. Something like g.gl. – HyperNeutrino – 2017-01-13T15:20:49.687

3You should also be able to just echo $? instead of that whole if statement. – SomethingDark – 2017-01-13T16:25:44.920

4you missed "some" ; in the golfed line. – Ipor Sircer – 2017-01-14T01:57:07.897

@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 – 2017-01-14T03:12:09.633

@AbelTom - it could be argued that 0 is truthy and non-0 is falsey. – SomethingDark – 2017-01-14T03:13:54.433

@SomethingDark Haha, i tried to negate the return value too, but I could not and don't know how. 0 is accepted as truthy? i mean would that be compliant with the spec ? – Abel Tom – 2017-01-14T03:20:15.373

Yeah, bash traditionally considers 0 to be success and everything else to be a failure

– SomethingDark – 2017-01-14T03:22:40.087

Also, I'm not sure why you're setting a variable at all; you can just say ping -c1 g.gl;echo $? (or to. instead of g.gl like some other people are doing) – SomethingDark – 2017-01-14T03:24:03.743

@SomethingDark I actually wanted to do that initially, but i thought output should be only either 0 or 1. There's some unwanted text too when i run this program, thats the reason i stored it in a variable. – Abel Tom – 2017-01-14T03:33:12.523

5

Java, 72 bytes

a->new java.net.InetSocketAddress("to.",80).getAddress().isReachable(9);

Huntro

Posted 2017-01-13T13:29:41.013

Reputation: 459

3You need to specify the fully qualified name java.net.InetSocketAddress – None – 2017-01-13T20:11:23.430

5

R, 20 bytes

curl::has_internet()

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

Billywob

Posted 2017-01-13T13:29:41.013

Reputation: 3 363

1+1 nice find. For those curious like me, this function is implemented as: function() !is.null(nslookup("r-project.org", error = FALSE)) – plannapus – 2017-01-14T16:15:32.753

Equivalent count: httr::url_ok('g.gl') (albeit deprecated). – Jonathan Carroll – 2017-01-16T01:17:19.553

4

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.

TheLethalCoder

Posted 2017-01-13T13:29:41.013

Reputation: 6 930

4

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.

Chaos Manor

Posted 2017-01-13T13:29:41.013

Reputation: 521

1TOS means top of stack. i think you mean it just leaves data on the stack. – Roman Gräf – 2017-01-13T20:17:13.967

That's right. I improved my explanation. Thanks. – Chaos Manor – 2017-01-13T20:26:59.033

@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 – 2017-01-14T08:09:51.250

4

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.

Dada

Posted 2017-01-13T13:29:41.013

Reputation: 8 279

Couldn't you switch to bash and remove the print? – BlueRaja - Danny Pflughoeft – 2017-01-13T17:20:11.403

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 – 2017-01-13T17:27:34.510

3

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.

Stewie Griffin

Posted 2017-01-13T13:29:41.013

Reputation: 43 471

3

Bash, 39 bytes

exec 4<>/dev/tcp/to./80&&echo 1||echo 0

G B

Posted 2017-01-13T13:29:41.013

Reputation: 11 099

1! exec 4<>/dev/tcp/to./80;echo $? – Jasen – 2017-01-14T00:15:00.950

or if you don't need to print true/false but can just return it,exec 4<>/dev/tcp/to./80 – Jasen – 2017-01-14T00:15:54.723

3

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

Zanchi

Posted 2017-01-13T13:29:41.013

Reputation: 31

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 – James – 2017-01-13T19:02:10.690

@DJMcMayhem How's your cache? – Ismael Miguel – 2017-01-13T19:30:50.173

@DJMcMayhem I tested in Chrome, Win10. Disabled cache from the network tab and checked Offline to test offline/online – Zanchi – 2017-01-13T20:07:54.793

This can be a full program in 52 bytes: fetch('://to.').then(a=>alert(1)).catch(a=>alert(0)) – Patrick Roberts – 2017-01-13T20:30:08.397

2

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

Christoph

Posted 2017-01-13T13:29:41.013

Reputation: 1 489

4Re "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). – None – 2017-01-13T17:51:07.753

Does an array count as truthy? I'll allow it to compete anyway though, since it is my question. Just out of interest. – Restioson – 2017-01-16T10:11:46.783

@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 – 2017-01-16T10:30:06.937

@Cristoph I don't think "Array" counts as truthy or falsey – Restioson – 2017-01-16T10:42:39.037

@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 – 2017-01-16T11:53:56.087

@Cristoph ah OK. Most langs I've seen do not do this afaik – Restioson – 2017-01-17T11:52:16.540

2

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

Horváth Dávid

Posted 2017-01-13T13:29:41.013

Reputation: 679

Test-Connection -Quiet to. – Shawn Esterman – 2017-01-13T15:34:27.637

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 – 2017-01-13T20:49:14.690

2

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

Tom

Posted 2017-01-13T13:29:41.013

Reputation: 3 078

2This answer implies that this won't always return false when not connected to the internet – Blue – 2017-01-13T14:57:04.917

You can save a byte by adding a parameter to the lambda, like so: f=a=> – XavCo7 – 2017-01-13T15:05:43.583

1Although your answer still seems to be invalid, you can get rid of f=. – Mama Fun Roll – 2017-01-13T15:13:24.410

178 bytes: a=>{with(new Image()){src="//placehold.it/1x1";onload=b=>a(1);onerror=c=>a()}}´ (got rid off=and usedwith(){}`) – Ismael Miguel – 2017-01-13T19:27:48.467

2

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.

corvus_192

Posted 2017-01-13T13:29:41.013

Reputation: 1 889

2

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.

Cody

Posted 2017-01-13T13:29:41.013

Reputation: 447

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 – 2017-01-14T06:54:47.650

2@Kos "I don't know" is not truthy/falsey – Restioson – 2017-01-15T09:42:50.187

It isn't "I don't know", it is "I can't therefore the answer is no" – Cody – 2017-01-17T16:36:40.097

maybe just print the byte '\0' since this is also 0. you would have a code of only 1 byte – 12431234123412341234123 – 2017-02-18T07:14:53.230

2

Python 3 + requests, 59 55 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)

matsjoyce

Posted 2017-01-13T13:29:41.013

Reputation: 1 319

You could shorten this by using a different protocol (ftp, perhaps), and doing except:0/0. – Mego – 2017-01-25T21:30:53.580

@Mego I think requests only does http(s). I've added the 0/0. – matsjoyce – 2017-01-25T21:56:16.837

1

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.

Chris H

Posted 2017-01-13T13:29:41.013

Reputation: 581

I think from urllib import* could save a char (and drop l. of course). – Nick T – 2017-01-13T23:04:18.310

@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 – 2017-01-14T08:27:13.073

1

Elixir, 33 bytes

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

0 if connected, 1 otherwise.

movsx

Posted 2017-01-13T13:29:41.013

Reputation: 21

1

Julia + Bash (with dnsutils), 10 bytes

run(`dig`)

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

Rɪᴋᴇʀ

Posted 2017-01-13T13:29:41.013

Reputation: 7 410

1

PowerShell, 12 bytes

!!(irm g.gl)

briantist

Posted 2017-01-13T13:29:41.013

Reputation: 3 110

1

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.

Kelly Lowder

Posted 2017-01-13T13:29:41.013

Reputation: 3 225

1Note that, by default, REPL snippets are not allowed. Put & afterwards to make it into an unnamed function. – LegionMammal978 – 2017-01-13T22:21:15.230

Can you point me to a link? – Kelly Lowder – 2017-01-13T22:45:57.497

See Default for Code Golf: Program, Function or Snippet?.

– LegionMammal978 – 2017-01-13T23:29:45.663

1In 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 – 2017-01-16T10:44:38.233

@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 – 2017-01-17T15:38:23.993

@KellyLowder Look up Mathematica scripts. In full programs, only values outputted with Print are actually put on STDOUT. – LegionMammal978 – 2017-01-17T23:37:03.737

0

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.

Carcigenicate

Posted 2017-01-13T13:29:41.013

Reputation: 3 295

0

Javascript (Nashorn), 61 bytes

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

Based on Huntro's Java answer.

SuperJedi224

Posted 2017-01-13T13:29:41.013

Reputation: 11 342