BACKGROUND: I now understand how to write a C# application that can monitor packets going in/out of the network card on the PC the application is running on. T
Personally I would stick to WinPCap. But since you asked, it is possible to sniff packets from the network using for the following code to enable raw sockets.
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
s.Bind(new IPEndPoint(IPAddress.Parse("<IP Address Here of NIC to sniff>"), 0));
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
byte[] inBytes = new byte[] { 1, 0, 0, 0 };
byte[] outBytes = new byte[] { 0, 0, 0, 0 };
s.IOControl(IOControlCode.ReceiveAll, inBytes, outBytes);
Once this is done, you can use Socket.Receive
or Socket.BeginReceive
to read the raw IP packets.
There is a way to capture incoming/outgoing packets on .NET using just the standard winsocks implementation. I've seen a blog with example of how but I don't have the link anymore.
Long story short, it's an extreme edge case because that's not what winsocks (the standard windows networking driver) was intended for.
The reason Pcap is usually necessary to capture packets is, it uses its own NDIS networking driver that unlocks the full capabilities of your NIC. On top of that, it also provides an easy way to set filters to limit the amount of packets being captured on the specified interface.
IE, the driver will ignore packets of a specific type at the kernel level instead of the usermode level. Therefore, you'll be able to filter packets much more efficiently and capture under larger loads on the network.
In .NET, to filter packets, you'd need to provide your own application layer packet filtering scheme that would be much less efficient.
Windows blocks access to non-standard protocols for 'security reasons' so they don't really support the use of RAW packets for networking (even though code may exist to make it possible). RAW packets were always intended for researching the design of new protocols, not general use.
For all of those reasons it is usually a good idea to pick up Winpcap and a wrapper for your specific language to implement any type of capturing application.
Note: I personally prefer SharpPcap, but I'm also biased as I do development on the project. Pcap.net is very similar in its implementation when it comes to capturing, it mainly diverges when it comes to how packets are parsed.