Check for Internet Connection

Posted by LiveToCollect, Posted on August 16, 2010, Last updated October 7, 2010

4 votes

Check for an internet connection if your app requires one.
I use this at app-launch and show the exit button to close the application if no net connection exists.

To test on iPhone, set to airplane mode and launch app.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
--------------------------------------------------------
-- Verify Net Connection
--------------------------------------------------------
local http = require("socket.http")
local ltn12 = require("ltn12")
 
if http.request( "http://www.google.com" ) == nil then
 
        local function onCloseApp( event )
        if "clicked" == event.action then
                os.exit()
        end
        end
 
        native.showAlert( "Alert", "An internet connection is required to use this application.", { "Exit" }, onCloseApp )
end

Compatibility: 
Corona 2.0

Replies

jonbeebe
User offline. Last seen 1 week 6 days ago. Offline
Joined: 26 Jul 2010

I have a news and updates button in the game I'm currently working on, so I use it to check for internet connection before loading a web popup (or else the app would be stuck on the web popup if there is no internet connection).

It works great--Thanks!

LiveToCollect
User offline. Last seen 9 weeks 1 day ago. Offline
Joined: 3 Feb 2010

@jonbeebe

Cool! I've ended up pulling this feature out of my app until they get it working asynchronously. Be sure to test on a slow connection, like Edge or 1 bar of 3G and you may notice a considerable delay in in the application while it's performing this check. Based user experience in my opinion.

Mine is setup now so that it just tried to load the web pop up no matter what. Worst case is the user sees the activity indicator for a while, which is better than nothing at all in the case of this current synchronous code that doesn't allow anything else to happen while it executes.

Hope this helps!

jwwtaker
User offline. Last seen 4 days 22 hours ago. Offline
Joined: 28 Apr 2010

If you dont have any connection it just spins forever. Is there some way to add a timeout so if it doesnt return in say 2 seconds it assumes no connection?

tjackiw
User offline. Last seen 14 weeks 6 days ago. Offline
Joined: 25 Aug 2010

An alternative that yields faster results is to use a pure socket connection:

1
2
3
4
5
6
------------------------------
-- Internet check via Socket
------------------------------
if require("socket").connect("google.com", 80) == nil then
        print("No connection")
end

jonbeebe
User offline. Last seen 1 week 6 days ago. Offline
Joined: 26 Jul 2010

@tjackiw: You're a life-saver! I was having problems with the other because it freezes if internet connection goes slow or get's cut off mid-app so thanks for the "via socket" tip!

LiveToCollect
User offline. Last seen 9 weeks 1 day ago. Offline
Joined: 3 Feb 2010

@tjackiw: Cheers, thanks!

cpeterson
User offline. Last seen 28 weeks 4 days ago. Offline
Joined: 15 Jun 2010

For the socket detection code, you might want to explicitly close the socket. Something like this:

1
2
3
4
5
6
7
8
local function testNetworkConnection()
    local google = require('socket').connect('google.com', 80)
    if google == nil then
        return false
    end
    google:close()
    return true
end

roottony
User offline. Last seen 7 weeks 5 hours ago. Offline
Joined: 27 Jun 2011

Even this one can freeze device for a couple of seconds (7..10..15 seconds). Especially if there is no internet.
As I understand, it runs in the same main thread... Pity..

So, the question of good internet connection check is still open :(

ezraanderson1979's picture
ezraanderson1979
User offline. Last seen 1 week 3 days ago. Offline
Joined: 8 Sep 2011

@cpeterson
@tjackiw

this is good code but if you are connected to a router through your devices wifi, but the router has no internet, it hangs the device for a short period of time.

i am also looking for a better solution, please post if you have one.

thx

ezraanderson1979's picture
ezraanderson1979
User offline. Last seen 1 week 3 days ago. Offline
Joined: 8 Sep 2011

test: device attached to router through wifi, router has internet turn off.

1
2
3
4
5
6
7
8
local function testNetworkConnection()
    local google = require('socket').connect('google.com', 80)
    if google == nil then
        return false
    end
    google:close()
    return true
end

crashes sometimes, or has a 60 second hang(timed out)

I have been using the above code and only noticed this because my internet was out today.

I have switched to the following code instead, maximum timeout is about 5seconds on the device.

It only works with the www.apple.com url, it seams to be buggy if you use a different url.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
--http://developer.anscamobile.com/reference/index/network/detect-network-status/networksetstatuslistener
 
function L.list_reachNet(event)
 
msg[#msg+1] = '>> L.list_reachNet'
 
 
--              print("address", event.address )
--              print("isReachable", event.isReachable )
--              print("isConnectionRequired", event.isConnectionRequired)
--              print("isConnectionOnDemand", event.isConnectionOnDemand)
--              print("IsInteractionRequired", event.isInteractionRequired)
--              print("IsReachableViaCellular", event.isReachableViaCellular)
--              print("IsReachableViaWiFi", event.isReachableViaWiFi)
 
                msg[#msg+1]  = "  @ address:                  \t\t".. tostring(event.address )
                msg[#msg+1]  = "  @ isReachable:              \t\t".. tostring(event.isReachable)
                msg[#msg+1]  = "  @ isConnectionRequired:    \t".. tostring(event.isConnectionRequired)
                msg[#msg+1]  = "  @ isConnectionOnDemand: \t".. tostring(event.isConnectionOnDemand)
                msg[#msg+1]  = "  @ IsInteractionRequired:    \t\t".. tostring(event.isInteractionRequired)
                msg[#msg+1]  = "  @ IsReachableViaCellular:   \t\t".. tostring(event.isReachableViaCellular)
                msg[#msg+1]  = "  @ IsReachableViaWiFi:       \t\t".. tostring(event.isReachableViaWiFi)
 
 
 
                        network.setStatusListener("www.apple.com", nil)
 
 
            if          event.isReachable == true then
 
                    --print('Yes Connection')
                    
                    msg[#msg+1]  ='  @ Connection: True'
                                        pipe.myReturn = r.next
                                        F.func_Checking()
                    
                    
 
            elseif      event.isReachable ==  false then
 
                    --print('No Connection')
                    
                    msg[#msg+1]  ='  @ Connection: False'
                                pipe.myReturn = r.failed
                                F.func_Checking()
 
            end
 
msg[#msg+1] = '<<'
 
 
end
 
 
 
 
function F.fn_testNetwork()
 
msg[#msg+1] = 'F.'..debug.getinfo(1, "n").name;
 
                if network.canDetectNetworkStatusChanges then
 
 
                        network.setStatusListener( 'www.appple.com', L.list_reachNet )
 
                else
                
                                --testing for windows simulator
                        F.fn_testGoogle()
                       -- print("network reachability not supported on this platform")
                end
 
 
 
end

i am still open for more suggestions because i don't think this code works on andriods.

thx