- Home /
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.
Perfect and excellent code.just put it on your camera in Start() and you are done.
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!
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
}
}
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
It Is Really works fine. Thank you so much (Y) (Y) (Y) .
Hello I am trying expecting too much but when I tested. I wonder if it can be added to a timeout?
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.
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
}));
}
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. :)
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.
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.
The better question is: "How do I check if I can reach my service?"
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.
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.
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?
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.
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.
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.
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.
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/
It seems silly to pay for this when you can just check Application.networkReachability
...
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.
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");
}
}
@ 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.
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?
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613121054im_/https://answers.unity.com/themes/thub/images/avi.jpg)