using System.Collections.Generic;
using System.Net.Sockets;
using System.Runtime.InteropServices;
private static string _fcaptureIp = "192.168.100.5";
private static Socket _fmainSocket = null;
private static int IpHeaderSize = 0;
private static byte[] _headerBytes = null;
static void Main(string[] args)
IpHeaderSize = Marshal.SizeOf(typeof(IpV4Header));
_fmainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
_fmainSocket.Bind(new IPEndPoint(IPAddress.Parse(_fcaptureIp), 0));
_fmainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
byte[] byTrue = new byte[4] { 1, 0,0,0};
byte[] byOut = new byte[4] ;
_fmainSocket.IOControl(IOControlCode.ReceiveAll, byTrue, byOut);
private static void recv()
byte[] buff = new byte[3000];
int count = _fmainSocket.Receive(buff);
var ipHeader = GetIpHeaderFromBytes(buff, 0, IpHeaderSize);
if(ipHeader.ip_srcaddr!= ipHeader.ip_destaddr)
Console.WriteLine($"From: { new IPAddress(ipHeader.ip_srcaddr)} To: { new IPAddress(ipHeader.ip_destaddr)}");
private static IpV4Header GetIpHeaderFromBytes(byte[] bytes, int offset, int headerSize)
var tmp = new List<byte>();
for (int i = offset; i < (offset + headerSize); i++)
byte[] headerBytes = tmp.ToArray();
GCHandle handle = GCHandle.Alloc(headerBytes, GCHandleType.Pinned);
(IpV4Header)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(IpV4Header));
[StructLayout(LayoutKind.Explicit)]
public ushort ip_totallength;
public ushort ip_checksum;