RobertPitt
RobertPitt

Reputation: 57268

Windows Service to watch network

I need to build a Windows Service to monitor the network (IP) and modify the proxy settings accordingly.

The service will be installed, and should watch the IPs to detect whether it's an internal or external IP.

I have created a basic Windows Service based on guides around the internet but I'm unsure what's the best way to go from here.

From the guides I noticed that the WindowsService object has some kind of event system, and I'm wondering if it's possible to hook into that?

Here's the basic code.

using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.ComponentModel;
using System.Configuration.Install;

namespace WindowsService
{
    [RunInstaller(true)]
    public class WindowsServiceInstaller : Installer
    {
        public WindowsServiceInstaller()
        {
            ServiceProcessInstaller SPI = new ServiceProcessInstaller();
            ServiceInstaller SI = new ServiceInstaller();

            //# Service Account Information
            SPI.Account = ServiceAccount.LocalSystem;
            SPI.Username = null;
            SPI.Password = null;

            //# Service Information
            SI.DisplayName = WindowsService._WindowsServiceName;
            SI.StartType = ServiceStartMode.Automatic;

            //# set in the constructor of WindowsService.cs
            SI.ServiceName = WindowsService._WindowsServiceName;

            Installers.Add(SPI);
            Installers.Add(SI);
        }
    }

    class WindowsService : ServiceBase
    {
        public static string _WindowsServiceName = "Serco External Proxy Manager";

        public WindowsService()
        {
            ServiceName = _WindowsServiceName;
            EventLog.Log = "Application";

            // These Flags set whether or not to handle that specific
            // type of event. Set to true if you need it, false otherwise.
            CanHandlePowerEvent = true;
            CanHandleSessionChangeEvent = true;
            CanPauseAndContinue = true;
            CanShutdown = true;
            CanStop = true;
        }

        static void Main()
        {
            ServiceBase.Run(new WindowsService());
        }

        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
        }

        protected override void OnStop()
        {
            base.OnStop();
        }

        protected override void OnPause()
        {
            base.OnPause();
        }

        protected override void OnContinue()
        {
            base.OnContinue();
        }
    }
}

Any help is appreciated

Upvotes: 0

Views: 1715

Answers (3)

Matt Davis
Matt Davis

Reputation: 46034

I, too, am unclear about modifying the proxy settings, but as for monitoring the network itself, I think I can help with that.

In order to monitor the IP traffic on the network, you'll want to create a "raw" (or promiscuous) socket. You have to have admin rights on the local box to create this kind of socket, but as long as your Windows Service is running under the System account, you should be ok (that's what I'm doing in my case, by the way).

To create a raw socket, do something like this:

using System.Net.Sockets;
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
s.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.1"), 0)); // use your local IP
byte[] incoming = BitConverter.GetBytes(1);
byte[] outgoing = BitConverter.GetBytes(1);
s.IOControl(IOControlCode.ReceiveAll, incoming, outgoing);
s.ReceiveBufferSize = 8 * 1024 * 1024;  // 8MB

You can now use this socket to receive all of the incoming and outgoing IP packets on the specified local IP address.

In your Windows Service, add the following fields:

using System.Threading;
private ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
private Thread _thread;
private Socket _socket;

In the OnStart() callback of your Windows Service, create the thread that will do the work:

protected override void OnStart(string[] args)
{
    _thread = new Thread(delegate() {
        // Initialize the socket here
        while (!_shutdownEvent.WaitOne(0)) {
            // Receive the next packet from the socket
            // Process packet, e.g., extract source/destination IP addresses/ports
            // Modify proxy settings?
        }
        // Close socket
    });
    _thread.Name = "Monitor Thread";
    _thread.IsBackground = true;
    _thread.Start();
}

In the OnStop() callback of your Windows Service, you need to signal the thread to shutdown:

protected override void OnStop()
{
    _shutdownEvent.Set();
    if (!_thread.Join(3000)) { // give the thread 3 seconds to stop
        _thread.Abort();
    }
}

Hopefully, that gives you enough to get started.

Upvotes: 1

Kieren Johnstone
Kieren Johnstone

Reputation: 42003

You'll need to define the part you're having problems with and phrase this as a specific question.

Here's what's on your TODO list:

  1. Determine IP addresses of the machine (there can be many), and make some judgement on them
  2. Modify proxy settings (presumably Internet Explorer proxy settings?)
  3. Integrate this functionality into a Windows Service, perhaps using a background thread

It's not clear from your question what you've already tried, perhaps you could give an example of a problem you've been having, what you've tried to do to solve it and someone will be able to provide some help.

Upvotes: 0

ChrisLively
ChrisLively

Reputation: 88064

Not sure about modifying the proxy settings, but for monitoring you'll need to use WMI.

Upvotes: 0

Related Questions