Search code examples
c#socketspacket-sniffers

Don't know why I'm getting Error Code 10022 (Invalid Argument) when setting socket options in my C# sniffer


I'm writing a packet sniffer as an exercise in learning .Net 4 socket development on in C#. My goal is to sniff IP packets coming in and out out my computer.

My problem is that I'm getting error code 10022, invalid argument, on my call to SetSocketOption. I don't see where I have an invalid argument. I have some admin privs on my computer, but perhaps I don't have enough. It's my work computer and the IT department is pretty strict. With that said, if it was a permissions problem I would expect a different exception.

I'm not sure what my next step should be to debug this problem. Anyone have an idea?

Here's the code follows:

public Sniffer()
{
    try
    {
        socket = new Socket(
            AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);

        IPAddress[] ipAddresses = Dns.GetHostEntry(
            Dns.GetHostName()).AddressList;

        socket.Bind(new IPEndPoint(ipAddresses[0], 0));

        socket.SetSocketOption(
            SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);

        byte[] inputData = new byte[4] { 1, 0, 0, 0 };
        byte[] outValue = new byte[4];

        socket.IOControl(IOControlCode.ReceiveAll, inputData, outValue);
    }
    catch (SocketException ex)
    {
        string ErrorMessage = ex.Message;
    }
}

Solution

  • Microsoft has restricted the use of raw sockets on non-server editions of the the windows OS on all OS's newer than XP SP2, due to abuse by viruses in the early 2000's.

    You can read more on what restrictions are in place from the page on TCP/IP Raw Sockets on the MSDN.