Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
15
Question by naglers · Nov 01, 2013 at 04:28 PM · network

How to 100% check internet availability

Ok I am posting this because it took me several days to figure out a way to check the internet properly. Pinging - could be disabled by the network i.e. unreliable

 public static bool HasConnection()
 {
     try
     {
         using (var client = new WebClient())
         using (var stream = new WebClient().OpenRead("http://www.google.com"))
         {
             return true;
         }
     }
     catch
     {
         return false;
     }
 }
 
 bool CheckConnection(string URL)
 {
     try
     {
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
         request.Timeout = 5000;
         request.Credentials = CredentialCache.DefaultNetworkCredentials;
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 
         if (response.StatusCode == HttpStatusCode.OK) return true;
         else return false;
     }
     catch
     {
         return false;
     }
 }

both of these methods returned true if connected and false if not connected but what if you were connected to a network but needed to log-in to view content still (getting routed to a log-in page when trying to browse) If that is the case then these methods will still return true since they got a response but it really didn't get the right one.

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image sharpg · May 07, 2015 at 07:04 PM -1
Share

Perfect and excellent code.just put it on your camera in Start() and you are done.

avatar image KEric · Mar 17, 2020 at 07:10 PM 0
Share

I've created an Android's library that can be used as Unity's plugin for this purpose. If anyone's interested it's available under https://github.com/rixment/awu-plugin Hope it helps, cheers!

11 Replies

· Add your reply
  • Sort: 
avatar image
18
Best Answer

Answer by naglers · Nov 01, 2013 at 04:36 PM

Using this method you can see if you are able to view the page you wanted or not by accessing the html of that page you can read it to see if you got redirected or not. this example uses www.google.com as it's check

 using System.Net;
 public string GetHtmlFromUri(string resource)
 {
     string html = string.Empty;
     HttpWebRequest req = (HttpWebRequest)WebRequest.Create(resource);
     try
     {
         using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
         {
             bool isSuccess = (int)resp.StatusCode < 299 && (int)resp.StatusCode >= 200;
             if (isSuccess)
             {
                 using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
                 {
                     //We are limiting the array to 80 so we don't have
                     //to parse the entire html document feel free to 
                     //adjust (probably stay under 300)
                     char[] cs = new char[80];
                     reader.Read(cs, 0, cs.Length);
                     foreach(char ch in cs)
                     {
                         html +=ch;
                     }
                 }
             }
         }
     }
     catch
     {
         return "";
     }
     return html;
 }

This is to call the function

 using System.Net;
 void Start()
 {
     string HtmlText = GetHtmlFromUri("http://google.com");
     if(HtmlText == "")
     {
         //No connection
     }
     else if(!HtmlText.Contains("schema.org/WebPage"))
     {
         //Redirecting since the beginning of googles html contains that 
         //phrase and it was not found
     }
     else
     {
         //success
     }
 }
Comment
Add comment · Show 16 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image naglers · Nov 01, 2013 at 04:37 PM 0
Share

This is the code I found help me answer this http://snipplr.com/view/17389/

this works on android 4.1 (tested) $$anonymous$$ake sure you change the API compatibility level under player settings - Other to Net2.0 ins$$anonymous$$d of the subset

avatar image sudhir_kotila · Aug 20, 2015 at 01:56 PM 0
Share

It Is Really works fine. Thank you so much (Y) (Y) (Y) .

avatar image viper_aykiri · Oct 15, 2015 at 05:09 PM 0
Share

Hello I am trying expecting too much but when I tested. I wonder if it can be added to a timeout?

avatar image Goodie848 · Mar 23, 2016 at 12:21 PM 0
Share

Excellent solution naglers, thanks for sharing it.

avatar image Wylie-Modro · Dec 31, 2016 at 09:03 PM 0
Share

Is there a reason this does not appear to work for any other test sites?

For example if I try it for Facebook or Twitter, GetHtmlFromUri() always seems to return "", as in no html is read at all.

Show more comments
avatar image
26

Answer by pixel_fiend · Jul 10, 2014 at 12:32 AM

I might be over-simplifying the issue, but this works for me:

 IEnumerator checkInternetConnection(Action<bool> action){
     WWW www = new WWW("http://google.com");
     yield return www;
     if (www.error != null) {
         action (false);
     } else {
         action (true);
     }
 } 

 void Start(){
     StartCoroutine(checkInternetConnection((isConnected)=>{
         // handle connection status here
     }));
 }
Comment
Add comment · Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image tonic · Jul 10, 2014 at 12:46 AM 0
Share

Have you tried what happens with public wifi login pages (in airport, hotel or so)?

With those you may get to make a "successful" www request, but the request ends up in wrong place and you get wrong data.

If you know you don't need to care for such cases, then your way should work fine. :)

avatar image ArmanOhanian · Jan 13, 2016 at 08:17 AM 2
Share

This method works for me too, with slight modifications/extension.

I am hitting an API endpoint on my own server, then checking to see if the returned text is what I expect.

avatar image Bunny83 ArmanOhanian · Feb 23, 2016 at 02:58 PM 1
Share

Yes, this is the closest you can get. There is no 100% since the "internet" itself is nothing you can reach. It's just a giant network. It's possible that in a certain network certain endpoints are restricted by firewalls / webfilters while others might only allow certain pages. Company wlans often have sites like facebook and some ga$$anonymous$$g sites blocked. Reaching google doesn't mean you can reach anything else.

Also using the google webpage for an internet reachability check might get you in trouble. Such a usecase usually counts as misuse of their services:

Don’t misuse our Services. For example, don’t [...] try to access them using a method other than the interface and the instructions that we provide.

Being able to"reach the internet" can't be simply answered with true / false. In most cases you need the internet to communicate with a certain service. So the best approach is to use your own server which returns something you can identify. Since there might be caches implemented in your route the simples way is to build an echo server. So you send a random string / number to your server and it simply sends it back as content.

Note: even if your server can't be reached, it doesn't tell you for sure that you can't access other things. Some countries censor the internet so it's possible that they block content from your country but not from others. Also possible the other way round.

avatar image ArmanOhanian Bunny83 · Oct 03, 2017 at 02:00 AM 2
Share

The better question is: "How do I check if I can reach my service?"

avatar image JasonC_ · May 18, 2021 at 12:09 AM 0
Share

Please don't use this solution; especially on mobile devices, as it will just sit around sucking up bandwidth downloading that page over and over, which is especially an issue with mobile devices that have limited data plans or limited bandwidth.

You rarely ever need to actually check the internet connection. In almost all cases, equally good UX can be achieved by simply notifying the user if your actual attempt to access a resource fails, without you having to monitor anything in the background.

avatar image tubelightboy · Aug 16, 2021 at 05:45 PM 0
Share

Is it a good idea/practice to run the coroutine in the update method to make sure the user cannot play the game if there is no connection? I don't want to overload the buffer or something like that.

avatar image
3
Wiki

Answer by abhishekdeb · Dec 25, 2013 at 06:46 AM

Great Code. Although I came across a major problem with this script. This script correctly shows result what it is intended for. I tried to make it check for connection avilability:

 public static bool IsConnected(string hostedURL="http://www.google.com")
 {
     try{
         string HtmlText = GetHtmlFromUri(hostedURL);
         if(HtmlText == "" )
             return false;
         else
             return true;
         }
     catch(IOException ex)
     {
         return false;
     }
 } 

It is working fine but, when the machine is offline, It freezes the application(Unity Editor) and after 10 seconds or so it resumes. Is there anyway I can implement a timeout feature so as to specifiy for how long will it check?

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image naglers · Jan 13, 2014 at 03:34 PM 1
Share

I call this function in an IEnumerator so ins$$anonymous$$d of

 void Start()
 {
   string str = GetHtmlFromUri("http://google.com");
    if(!str.Contains("schema.org/WebPage"))
 }

you use

 void Start()
 {
   StartCoroutine(SendEmail());
 }
 IEnumerator SendEmail()
 {
   string str = GetHtmlFromUri("http://google.com");
    if(!str.Contains("schema.org/WebPage"))
 }

that way if you don't get what you want then you can break out whenever you want. and if you don't get an answer within a specific amount of time you can break out then too.

avatar image youblistermypaint naglers · Jul 09, 2016 at 03:57 PM 0
Share

Would a coroutine do anything here? You don't have an yield statements in GetHtmlFromUri so it wouldn't return control flow to the calling behavior until it was finished.

I think you would need to use a C# thread in this case to ensure it didn't block.

avatar image JasonC_ · May 18, 2021 at 12:10 AM 2
Share

You could just not check for internet availability; and instead just display an error to the user if it fails when you actually try to access the resource.

avatar image shacharoz · Nov 20, 2021 at 02:56 PM 0
Share

im sorry but the solution doesnt work. even on the editor, if you shut down the connection, there is a big lag in the response. it also occurs on an ios device.

avatar image
3

Answer by tonic · Dec 29, 2014 at 12:23 PM

This asset is an easy solution, with support to use major company network accessibility detection urls in addition to having the option to using your own: Internet Reachability Verifier https://strobotnik.com/unity/internetreachabilityverifier/

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image JasonC_ · May 18, 2021 at 12:18 AM -1
Share

It seems silly to pay for this when you can just check Application.networkReachability...

avatar image tonic JasonC_ · May 18, 2021 at 08:20 AM 1
Share

Application.internetReachability just tells "which options are available" as it's said in the docs. That's like a check to see if wifi or carrier data is enabled at all (on a mobile device). But to actually know if network works, you have to do a request and verify results. Even the request may succeed, but results can be wrong, this happens if you're behind a captive portal requesting to login to the network first (e.g. hotel/airport). Internet Reachability Verifier helps with this whole picture.

avatar image
2

Answer by ODNSEV7N · Dec 29, 2014 at 11:53 AM

Heres my way if it helps, it works fine for me.

 var url : String = "I used a google docs page with one character here";
 
 function Start(){
    var www : WWW = new WWW(url);
    yield www;
    if(www.isDone && www.bytesDownloaded > 0){
    print("done");
    }
 if(www.isDone && www.bytesDownloaded == 0){
    print("no connection");
 
    }
 
 }
Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image OJ3D · May 04, 2016 at 05:27 AM 0
Share

@ ODNSEV7N - Like your method. Straight and Simple. I used a small pic 8 x 8 px pic. Small in size and You'd need internet to retrieve it . It's a quick and dirty check that would not only require a network check but internet to retrieve any bytes.

avatar image chocolikegames · Jan 25, 2018 at 12:39 PM 0
Share

Hello, a very handsome solution. (I will assign this code to a button, and show the UnityAds where the print is written, or close the window.) What should I do when I want to call this method with the button? I assigned this script to an empty game object, then I did not know which function to call. I'm very happy if you help. So what I want to know is how can we call this function with just button?

avatar image JasonC_ · May 18, 2021 at 12:15 AM 1
Share

I just checked this. A Google Docs page with 1 character is a 3.5MB download after a cache clear.

Please don't use this solution; especially on mobile devices, as it will just sit around sucking up bandwidth downloading that page over and over, which is especially an issue with mobile devices that have limited data plans or limited bandwidth.

You rarely ever need to actually check the internet connection. In almost all cases, equally good UX can be achieved by simply notifying the user if your actual attempt to access a resource fails, without you having to monitor anything in the background.

  • 1
  • 2
  • 3
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

47 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Is web site available from within a scene 0 Answers

Lerp: inconsistent movement(multiplayer related) 1 Answer

Nerworking communication between two exes in two different systems? 0 Answers

WWW.texture provides a :"?" texture... 1 Answer

How to tell when I've received the Server's state after the client connects 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges