Programmatically Finding, Connecting to, and Disconnecting from VPNs

WEBINAR: On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

VPN

A VPN (Virtual Private Network) extends a private network across a public network, and enables users to send and receive data across shared or public networks similar to being directly connected to a private network. This provides a few benefits to applications running across the VPN. These benefits include:

  • Functionality
  • Security
  • Management of the private network

Virtual Private Networks allow employees to securely access a corporate Intranet while located outside the office. VPNs are used to securely connect geographically separated offices of an organization, thus creating a cohesive network. On the other side, Internet users could secure their wireless transactions with a VPN. In doing so, geo-restrictions and censorship are circumvented.

System.Net.NetworkInformation

The .NET Framework includes the System.Net.NetworkInformation namespace, which provides access to network traffic data, network address information, and notification of address changes for the local computer. The System.Net.NetworkInformation namespace also contains classes that implement the Ping utility that can used to check whether a computer is reachable across a network.

NetworkInterface.GetAllNetworkInterfaces

The NetworkInterface class provides configuration and statistical information for a network interface. And, the getAllNetworkInterfaces method returns objects that describe the network interfaces on the local computer.

RasPhone and RasDial

RasPhone is a wrapper around the Win32 RasPhonebookDlg API, and is typically used when an interface may be allowed. RasDial is a wrapper around the Win32 RasDial API, and is typically used in situations where no user interface can be shown.

Our Project

The aim of today's project is to show you different ways you can determine a VPN connection and some methods on how to disconnect and connect to a VPN. Start a new Visual Basic Windows Forms project and add two buttons onto the form.

Code

Open the code window and add the necessary Namespace to your project:

Imports System.Net.NetworkInformation

Add the following sub procedure:

   Private Sub CheckConnection()

      Dim niVPN As NetworkInterface() = _
         NetworkInterface.GetAllNetworkInterfaces

      Dim blnExist As Boolean = _
         niVPN.AsEnumerable().Any(Function(x) x.Name = "VPN Name")

      If blnExist Then

         MessageBox.Show("VPN Exists")

      Else

         MessageBox.Show("VPN Does Not Exist")

      End If

   End Sub

This is probably the easiest and most convenient way of determining whether or not you have a VPN connection. It makes use of the NetworkInterface class and uses LINQ to loop through all the known network interfaces. If a VPN connection exists, it returns true; else, false. Use this sub procedure when button 1 has been clicked:

   Private Sub Button1_Click(sender As Object, e As EventArgs) _
         Handles Button1.Click

      CheckConnection()

   End Sub

Add a new class to your project and name it anything simple, such as clsVPN. Add the following members to your clsVPN class:

   Private strRASPhone As String = _
      "C:\WINDOWS\system32\rasphone.exe"
   Private strVPNCon As String = ""
   Private strIPAddress As String = ""

   Private blnConnected As Boolean = False

Here, you get access to the RasPhone object, and enable your application to store the connection string and IP Address. Add the following Delegates and Events:

   Public Delegate Sub delPing()
   Public Delegate Sub delConnect()
   Public Delegate Sub delIdle()
   Public Delegate Sub delDisconnect()
   Public Delegate Sub delStatus(blnConnected As Boolean)

   Public Event Ping As delPing
   Public Event Con As delConnect
   Public Event Discon As delDisconnect
   Public Event Idle As delIdle
   Public Event StatusChanged As delStatus


   Protected Sub OnStatusChanged(blnConnected As Boolean)

      RaiseEvent StatusChanged(blnConnected)

   End Sub

   Protected Sub OnDisconnect()

      RaiseEvent Discon()

   End Sub

   Protected Sub OnPing()

      RaiseEvent Ping()

   End Sub

   Protected Sub OnIdle()

      RaiseEvent Idle()

   End Sub

   Protected Sub OnConnect()

      RaiseEvent Con()

   End Sub

Add the following Properties to your class:

   Public ReadOnly Property Connected() As Boolean

      Get

         Return blnConnected

      End Get

   End Property


   Public Property ConName() As String

      Get

         Return strVPNCon

      End Get

      Set(strValue As String)

         strVPNCon = strValue

      End Set

   End Property

The properties keep track of the Connection name and Connected state. Connect to the VPN:

   Private Function Connect() As Boolean

      Dim blnSucceed As Boolean = False

      OnConnect()

      Process.Start(strRASPhone, Convert.ToString(" -d ") _
         & strVPNCon)

      Application.DoEvents()

      System.Threading.Thread.Sleep(5000)

      Application.DoEvents()

      blnSucceed = True

      OnIdle()

      Return blnSucceed

   End Function

Test the Connection

   Public Function Test() As Boolean

      Dim blnSucceed As Boolean = False

      OnPing()

      Dim p As New Ping()

      If p.Send(strIPAddress).Status = IPStatus.Success Then

         blnSucceed = True

      Else

         blnSucceed = False

      End If

      p = Nothing

      If blnSucceed <> blnConnected Then

         blnConnected = blnSucceed

         OnStatusChanged(blnConnected)

      End If

      OnIdle()

      Return blnSucceed

   End Function

Disconnect

   Private Function Disconnect() As Boolean

      Dim blnSucceed As Boolean = False

      OnDisconnect()

      Process.Start(strRASPhone, Convert.ToString(" -h ") _
         & strVPNCon)

      Application.DoEvents()

      System.Threading.Thread.Sleep(8000)

      Application.DoEvents()

      blnSucceed = True

      OnIdle()

      Return blnSucceed

   End Function

Add the following code to test the connection from your Form:

   Private Sub Button2_Click(sender As Object, e As EventArgs) _
         Handles Button2.Click

      Dim vp As New clsVPN

      vp.Test()

      If vp.Connected Then

         MessageBox.Show("Connected")

      Else

         MessageBox.Show("Not Connected")

      End If

   End Sub

The code for this article is available on GitHub.

Conclusion

The System.Net.NetworkInformation Namespace is very powerful. Detecting network connections and whether or not your are making use of a VPN can come in quite handy.



About the Author

Hannes DuPreez

Hannes du Preez is an ex MVP for Visual Basic from 2008 to 2017. He loves technology and loves Visual Basic and C#. He loves writing articles and proving that Visual Basic is more powerful than what most believe. You are most welcome to reach him at: ojdupreez1978[at]gmail[dot]com

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date