Skip to content

Commit

Permalink
Create RasApi.DisconnectAll() function.
Browse files Browse the repository at this point in the history
  • Loading branch information
rinrab committed Jan 20, 2024
1 parent 0931d05 commit a7c4a36
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 0 deletions.
25 changes: 25 additions & 0 deletions AOVpnManager.Tests/RasApiTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;

namespace AOVpnManager.Tests
{
[TestClass]
public class RasApiTests
{
[TestMethod]
public void HangupAllTest()
{
if (!Debugger.IsAttached)
{
return;
}

RasApi.DisconnectAll((x) =>
{
Console.WriteLine(x);
return true;
});
}
}
}
74 changes: 74 additions & 0 deletions AOVpnManager/RasApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace AOVpnManager
{
public static class RasApi
{
public static void DisconnectAll(Predicate<string> filter)
{
uint dwSize = (uint)Marshal.SizeOf(typeof(RASCONN));
uint count = 1;
RASCONN[] connections;
while (true)
{
uint cb = dwSize * count;
connections = new RASCONN[count];
connections[0].dwSize = dwSize;

int err = RasEnumConnections(connections, ref cb, ref count);

if (err == 0)
{
break;
}
else if (err != ERROR_BUFFER_TOO_SMALL)
{
throw new Win32Exception(err);
}

count = (cb + dwSize - 1) / dwSize;
}

for (int i = 0; i < count; i++)
{
if (filter(connections[i].szEntryName))
{
RasHangUp(connections[i].hrasconn);
}
}
}

const int RAS_MaxEntryName = 256;
const int RAS_MaxDeviceType = 16;
const int RAS_MaxDeviceName = 128;

const int ERROR_BUFFER_TOO_SMALL = 603;

[StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Auto)]
private struct RASCONN
{
public uint dwSize;

public IntPtr hrasconn;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = RAS_MaxEntryName + 1)]
public string szEntryName;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = RAS_MaxDeviceType + 1)]
public string szDeviceType;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = RAS_MaxDeviceName + 1)]
public string szDeviceName;

// We don't care about other feilds.
}

[DllImport("Rasapi32.dll", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = false)]
private static extern int RasEnumConnections([In, Out] RASCONN[] connections, ref uint cb, ref uint count);

[DllImport("Rasapi32.dll", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = false)]
private static extern int RasHangUp(IntPtr rasconn);
}
}

0 comments on commit a7c4a36

Please sign in to comment.