我之前使用 python 创建了一个简单的数据包嗅探器,代码如下:
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)
在一个循环中,它打印出接收到的数据包数据的大小(以字节为单位)以及发送方和端口的 ip 地址。我正在尝试使用 C++ 重新创建该程序,这是我目前所做的:
#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;
}
我对c++中的套接字编程不是很熟悉。当我运行程序时,没有输出被打印出来。我试过循环运行程序,看看是否恰好在那个时间没有任何传入的数据包,但仍然没有运气。我运行程序时没有发生错误。
函数式编程
MYYA
相关分类