Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Getting packet data

I've been trying to write a script that will sniff HTTP headers. So far I've got the socket bound to port 80 and packets seem to be received, but I can't get them into string form. All that outputs is "E" continuously. I changed the bytes into hex earlier and there seems to be some data coming in, but the current code is unable to change the bytes into a string. Is there some other way of decoding the bytes that will give a proper string?

byte[] input = BitConverter.GetBytes(1);
byte[] buffer = new byte[4096];
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
s.Bind(new IPEndPoint(IPAddress.Parse(strIP), 80));
s.IOControl(IOControlCode.ReceiveAll, input, null);
int bytes;
bytes = s.Receive(buffer);
while (bytes > 0)
{
    log(System.Text.Encoding.ASCII.GetString(buffer, 0, bytes));
    bytes = s.Receive(buffer);
}
like image 420
James Avatar asked Dec 05 '22 04:12

James


2 Answers

When you sniff data using a raw socket, you're receiving Internet Protocol (IP) packets. Each IP packet begins with an IP header. This header is typically 20 bytes long, but it can be longer than that. Following the IP header is the header for the Transport Layer, e.g., the Transmission Control Protocol (TCP) header or the User Datagram Protocol (UDP) header. After this header comes the data you're looking for, i.e., the HTTP. So when you're parsing the data, you need to skip past the IP header and the Transport Layer header first.

like image 109
Matt Davis Avatar answered Dec 24 '22 01:12

Matt Davis


You might want to checkout the source code for this C# network sniffer, here.

like image 35
BrainCore Avatar answered Dec 24 '22 02:12

BrainCore