NAVmoble - the pocket-sized ERP
Optimized for Microsoft Dynamics NAV and Windows Mobile powered devices

Friday, December 01, 2006

"How To" Series: Detect network connection in Compact Framework

There is several ways to accomplish this and I will outline some of them in this post.


The following snippet may be used to detect if the device is connected to a network.
It checks if the device has an IP address assigned. This approach will not work properly if the device has a static IP. It is not guaranteed that a specific network destination is reachable.


bool IsConnected
{
    get
    { 
        try
        {  
            string hostName = Dns.GetHostName(); 
            IPHostEntry curHost = Dns.GetHostByName(hostName); 
            return curHost.AddressList[0].ToString() != IPAddress.Loopback.ToString(); 
        } 
        catch
        {
            return false; 
        }
    }
}


Another possible approach is to check if there is a "path" to a specific destination.


public bool IsNetworkPathAvailable(string destinationAddress)
{
     bool connected = false
     HttpWebRequest request;
     HttpWebResponse response;
     try
     {
          request = (HttpWebRequest)WebRequest.Create(destinationAddress);
          response = (HttpWebResponse)request.GetResponse();
          request.Abort(); 
          if (response.StatusCode == HttpStatusCode.OK)
         {
              connected = true;
         }
    }
    catch (WebException ex)
    {
        connected = false;
    }
    catch (Exception ex)
    {
       connected = false;
    }
    finally
    {
       if(response != null)
          response.Close();    
    }
    return connected;
 }
//here we will use the network detection
if(IsNetworkPathAvailable(http://www.ritsoftware.com"))
            SendSomeDataOverTheWire();  


Another way to accomplish this is to use the InternetGetConnectedState function from wininet.dll
[DllImport("wininet.dll")]
private static extern bool InternetGetConnectedState(ref uint flags, uint dwReserved);

public bool IsConnected
{
   get
   {
        uint flags;
        return InternetGetConnectedState(ref flags,0);
   }
}  


 


Links
ConnectionManager class from www.opennetcf.org
Compact Framework Newsgroups


 


 


 

No comments: