Programmatically Finding, Connecting to, and Disconnecting from VPNs

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:WINDOWSsystem32rasphone.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.

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read