'Creating packet sniffer in c++
I have before created a simple packet sniffer using python, with the following code:
import socket
import os
import time
host = "192.168.0.164"
if os.name == "nt":
socket_protocol = socket.IPPROTO_IP
else:
socket_protocol = socket.IPPROTO_ICMP
while True:
sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
sniffer.bind((host, 0))
sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
out = sniffer.recvfrom(65565)
print("recieved {0} bytes from: {1}:{2}".format(len(out[0]), out[1][0], out[1][1]))
sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
In a loop it prints out the size in bytes of the recieved packet data and the ip adress of the sender and port. Im trying to recreate this program using c++ and this is what i have go so far:
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <Mstcpip.h>
#include <iostream>
#include <windows.h>
#define PORT 0
struct sockaddr_in address;
SOCKET sock;
const char opt = 0;
u_long mode_on = RCVALL_ON;
u_long mode_off = RCVALL_OFF;
char buffer;
int main()
{
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
sock = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
setsockopt(sock, IPPROTO_IP, IP_HDRINCL, &opt, sizeof(opt));
bind(sock, (struct sockaddr*) & address, sizeof(address));
ioctlsocket(sock, SIO_RCVALL, &mode_on);
recv(sock, &buffer, 65565, 0);
std::cout << buffer << std::endl;
ioctlsocket(sock, SIO_RCVALL, &mode_off);
return 0;
}
I am not very familiar with socket programming in c++. When i run the program no output is being printed out. I have tried running the program in a loop to see if it just was that there wasnt any incoming packet at exactly that time but still no luck. There are no errors occuring when i run the program.
Solution 1:[1]
I would recommend that you review some complete examples of configuring and reading from a socket. The example provided here appears to be not only complete, but the page specifies expected return values for the receive function.
Additionally, you are not initializing your buffer properly. You are essentially allotting 8 bits of data, then telling the receive function that it has 65565 bytes to fill (did you mean 2^16 which would give you 65536 (or 65535 accounting for buffer zero based indexing)?).
One last thing: the code which you provided in python appears to be intended to work on multiple platforms, but the C++ code will only compile for Windows. I would recommend focusing on getting this to work on a single platform before attempting to transfer it to any others.
Solution 2:[2]
He take the max buffer size ??
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alex Baum |
Solution 2 | King Tyson |