I just buildet a simple networksniffer in c#. Its working fine but im only capturing udp packets (i want to sniff for http packets). i thing i should change the socketinformation but i dont know how. btw is the ip address correct(i already chacked that). here is the source code:
static Socket socket;
static byte[] data = new byte[4096];
static void Main(string[] args)
{
IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[3];
socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
socket.Bind(new IPEndPoint(ip, 80));
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
socket.IOControl(IOControlCode.ReceiveAll, new byte[4] { 1, 0, 0, 0 }, new byte[4] { 1, 0, 0, 0 });
socket.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(receive), null);
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
}
static void receive(IAsyncResult ar)
{
int nReceived = socket.EndReceive(ar);
MemoryStream ms = new MemoryStream(data, 0, nReceived);
BinaryReader br = new BinaryReader(ms);
byte protocol = br.ReadBytes(10)[9];
if (protocol == 17)
{
//udp
}
else if (protocol == 6)
{
//tcp
}
else
{
//something else
}
data = new byte[4096];
socket.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(receive), null);
}