# [C#] Raw sockets packet sending



## xlink (Jan 31, 2010)

So I made a sniffer to suit my needs but now I want to try something more ambitious, I want to send back a packet that I filtered exactly the same, this is trickier than I thought.


```
IPAddress ip = IPAddress.Parse("192.168.2.100");

                    m_clientSocket = new Socket(ip.AddressFamily, SocketType.Raw, ProtocolType.Ip);                    

                    m_clientSocket.Bind(new IPEndPoint(ip, 0));

                    m_clientSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
```

Once I captured a packet that I want to resend I first write it to be sure that i got it and then try to send it.


```
byte[] dat = tcph.Data;

                    if (tcph.DataLength > 0)
                    {


                        char x = (char)dat[tcph.DataLength - 2];
                        string y = "" + x;
                        this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { y + "\n" });
                     

                    IPEndPoint ipEnd = new IPEndPoint(header.DestinationAddress, 8687);

                    try
                    {
                        m_clientSocket.SendTo(data, ipEnd);
                    }
                    catch (SocketException e)
                    {
                        MessageBox.Show(e.Message);
                    }
                    }
```


Thing is it doesn't send any packets nor does it result in an error, i have no clue what's the problem and there seems to be no documentation on C# raw packet sending on the internet.


----------



## robal (Feb 3, 2010)

Hi,

I'm no C# expert, but I worked with M$ Sockets for a while.

I'm not sure whether it's affecting you, but MS locked the possibility of "forging" packets using Socket API, to prevent kids from writing spoofing tools easily 

The move is plainly stupid, because you can still forge packets using lower-level access to the network driver (NDIS - in case of Windows)
Well...  that's what NIC is for...  creating packets...    Don't ask me to explain Microsoft's reasoning....

The easiest way to achieve this is to use API that will talk to the NDIS driver for you.
Use WINPCAP. It's free and fairly easy to use.

Cheers,


----------



## xlink (Feb 4, 2010)

Thanks, i knew about winpcap but i thought i could do it just with raw sockets cuz winpcap isn't native for c#.

Anyway i'll look into a winpcap wrapper of some sort.


----------

