I have an application that was written for remote trucks to use on cell service. Before I do anything, I am checking the internet with this class:
using System.Net;
namespace SSS.ServicesConfig.MiscClasses
{
public class VerifyInternetAccess
{
public static bool HasInternet()
{
try
{
using (var client = new WebClient())
using (var stream = client.OpenRead("http://www.google.com"))
{
return true;
}
}
catch
{
return false;
}
}
}
}
In some cases, the light on the external cellular device has a green light as if it has internet. My test class comes back false so it thinks it does not have internet.
The driver can then open up internet explorer, close internet explorer, promptly run my application and it passes the test above.
The users are saying that IE is 'waking up' the internet so that it can transfer.
Doesn't my class do essentially the same thing? If not, how can I 'wake up' the internet connection as IE does?
You didn't state if you're restricted to a certain mobile OS but this works on a normal box. I try to leverage two features of the System.Net.NetworkInformation namespace.
I start with registering for the NetworkChangedEvent. By calling GetIsNetworkAvailable you get an idea if there is at least one other NIC present that is not the loopback interface.
If there is no connection I try to wake-up the network layer by getting pinging a host. I use the Dns.GetHostEntry to obtain all IP Adresses known for a host. Next I try to Ping the address one by one.
Be aware that not all hosts allow ICMP traffic which would lead to timeouts in all circumstances. If however in the meantime the network becomes available the NetworkChanged event should have been fired and set the HasConnection
to true
public class VerifyInternetAccess
{
private static bool HasConnection = false;
static VerifyInternetAccess()
{
NetworkChange.NetworkAvailabilityChanged += (o, ca) =>
{
HasConnection = ca.IsAvailable;
};
HasConnection = NetworkInterface.GetIsNetworkAvailable();
}
public static bool HasInternet()
{
bool hasEnded = false;
if (!HasConnection)
{
// let's try to wake up...
using (var ping = new Ping())
{
var iphost = Dns.GetHostEntry("www.google.com");
foreach (var addr in iphost.AddressList)
{
var reply = ping.Send(addr);
if (reply.Status == IPStatus.Success)
{
HasConnection = true;
break;
}
}
}
}
return HasConnection;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With