Problem disconnecting OpenVpn from application

2019-09-10 02:02发布

问题:

I am tring to connect a remote server via openvpn using C#. I am able to connect it successfully. but disconneecting seems to not work properly. Once I close my app, I am not able to access the internet. I got to manually disable the TAP Adapter and then enable to execute the app again. I checked my "route print" and yes Tap is coming ahead of internet and hence couldn't access net.

I connect using : openvpn --config client.ovpn --ca certificate.cer --auth-user-pass user.txt

My disconnecting code is :

    public void DisconnectServer()
    {
        // Write the logs
        if (sb != null)
            IOUtility.WriteToFile(sb.ToString(), "ConnectionLogs.log");
        processInfo = null;
        if (process != null)
        {
            //process.Close();
            if (!process.HasExited)
            {
                process.CancelOutputRead();
                ProcessThreadCollection ptc = process.Threads;
                Console.WriteLine("////// PROCESSED THREAD = " + ptc.Count);
                for (int i = 0; i > ptc.Count; i++)
                {
                    ProcessThread pt = ptc[i];
                    pt.Dispose();
                    ptc.Remove(pt);
                    Console.WriteLine("REmoed Thread @ " + i);
                }
                process.CloseMainWindow();
                process.Kill();
            }
        }

        sb = null;
        connected = false;
    }

On searching net for this issue, I found to use management to exit the openvpn safely. But I cannot make how to run the managemetn code. While start I added : openvpn --config ca.ovpn --ca cert.cer --management 127.0.0.1 12345 Then how to give SIGTERM signal to close the openvpn. In new cmd, I tried : openvpn --management-signal SIGTERM but things doesn't work.

OpenVpn will not be installed as a Service, so I guess can't use --service attribute.

Can anyone guide me where am I going wrong in disconnecting. How to handle the managemetn-signal code. Which is the best way to disconnet from openvpn server. Can I also exit the openvpn itself ?

Kindly help me. Have searched a lot on internet and found some help but no sucess yet. Stuck on this issue.

Thanks

回答1:

Thanks to all,

I found the solution and this is how I suceeded :

            foreach (Process p in Process.GetProcesses())
        {
            if (p.ProcessName.StartsWith("openvpn"))
            {
                p.Kill();
                Console.WriteLine("Killed Process");
                break;
            }
        }

Instead of working with its thread and all, the above code helped out to solve the problem.

I hope this helps others too.