I would like to sniff packet data using C# I need it to sniff all types of data not only HTTP
When I try to do it I get this error:
System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.Bind(EndPoint localEP)
public void StartCapture(string InterfaceIp)
{
try
{
//Start capturing the packets...
//For sniffing the socket to capture the packets has to be a raw socket, with the
//address family being of type internetwork, and protocol being IP
mainSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
System.Net.Sockets.SocketType.Raw, System.Net.Sockets.ProtocolType.IP);
//Bind the socket to the selected IP address
mainSocket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(InterfaceIp), 0));
//Set the socket options
mainSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.IP, //Applies only to IP packets
System.Net.Sockets.SocketOptionName.HeaderIncluded, //Set the include the header
true); //option to true
byte[] byTrue = new byte[4] { 1, 0, 0, 0 };
byte[] byOut = new byte[4] { 1, 0, 0, 0 }; //Capture outgoing packets
//Socket.IOControl is analogous to the WSAIoctl method of Winsock 2
mainSocket.IOControl(System.Net.Sockets.IOControlCode.ReceiveAll, //Equivalent to SIO_RCVALL constant
//of Winsock 2
byTrue,
byOut);
//Start receiving the packets asynchronously
mainSocket.BeginReceive(byteData, 0, byteData.Length, System.Net.Sockets.SocketFlags.None,
new AsyncCallback(OnReceive), null);
}
catch (Exception ex)
{
//Report Exception
}
}
Note:I am using ASP.Net & it is really important to sniff the data and not only the headers of the packet
I think the problem is related to not having the right privileges to access to socket, although using impersonation didn't solve the problem
I found the solution to my problem, it's related to a recent implementation that limits binding to a socket that is protected and limited to a single ip address
Here are some interesting links
http://msdn.microsoft.com/en-us/library/cc150667(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ms740668%28v=VS.85%29.aspx