Not sure if you're interested in third party libraries, but you can use SharpPCap, which wraps around WinPCap calls. I would suggest reading the article to understand what it can do.
http://www.codeproject.com/Articles/12458/SharpPcap-A-Packet-Capture-Framework-for-NET
Example from the article (simplified):
// Extract a device from the list
ICaptureDevice device = devices[i];
// Open the device for capturing
int readTimeoutMilliseconds = 1000;
device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
Console.WriteLine();
Console.WriteLine("-- Listening on {0}...",
device.Description);
Packet packet = null;
// Keep capture packets using GetNextPacket()
while((packet=device.GetNextPacket()) != null )
{
// Prints the time and length of each received packet
DateTime time = packet.PcapHeader.Date;
int len = packet.PcapHeader.PacketLength;
Console.WriteLine("{0}:{1}:{2},{3} Len={4}",
time.Hour, time.Minute, time.Second,
time.Millisecond, len);
}
// Close the pcap device
device.Close();
Console.WriteLine(" -- Capture stopped, device closed.");
Note that received packet in this means packet received by WinPCap. It doesn't indicate the direction that the packet is going. This includes inbound and outbound traffic, which you can distinguish by the source and destination IP.
This would require whatever machine you're running on to have WinPCap installed. WinPCap is what Wireshark utilizes to capture packets.
Edit: If you wish to use raw sockets, try this:
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
if (_localIp != null)
_socket.Bind(new IPEndPoint(_localIp, 0));
_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
var receiveAllOn = BitConverter.GetBytes(1);
_socket.IOControl(IOControlCode.ReceiveAll, receiveAllOn, null);
_socket.ReceiveBufferSize = (1 << 16);
Read();
I didn't work on this code directly, but it's definitely being used and seems to be working: https://github.com/lunyx/CasualMeter/blob/master/NetworkSniffer/IpSnifferRawSocketSingleInterface.cs
Also needs to be run as admin with Windows firewall off: https://github.com/lunyx/CasualMeter/pull/47