代码可以捕获UDP传入/传出数据包和TCP传出数据包,但无法捕获Windows10上的任何TCP传入数据包。 但是,它在Windows XP上运行良好。
sniffer = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
if (sniffer == INVALID_SOCKET) {
printf("Failed to create raw socket.\n");
return 1;
}
memset(&dest, 0, sizeof(dest));
memcpy(&dest.sin_addr.s_addr, local->h_addr_list[in], sizeof(dest.sin_addr.s_addr));
dest.sin_family = AF_INET;
dest.sin_port = 0;
printf("\nBinding socket to local system and port 0 ...");
if (bind(sniffer, (struct sockaddr *)&dest, sizeof(dest)) == SOCKET_ERROR) {
printf("bind(%s) failed.\n", inet_ntoa(addr));
return 1;
}
printf("Binding successful");
//Enable this socket with the power to sniff : SIO_RCVALL is the key Receive ALL ;)
j = 1;
printf("\nSetting socket to sniff...");
if (WSAIoctl(sniffer, SIO_RCVALL, &j, sizeof(j), 0, 0, (LPDWORD)&in, 0, 0) == SOCKET_ERROR) {
printf("WSAIoctl() failed.\n");
perror("Error:");
return 1;
}
printf("Socket set.");
//Begin
printf("\nStarted Sniffing\n");
printf("Packet Capture Statistics...\n");
StartSniffing(sniffer); //Happy Sniffing
//End
closesocket(sniffer);
WSACleanup();
然后,我尝试用C#编写的https://www.netresec.com/?page=RawCap,与C ++代码的结果相同。
最后,我在python中尝试了raw socket,它在Win10上运行得很好。
import socket
from struct import *
host = '10.0.0.18'
# create a raw socket and bind it to the public interface
socket_protocol = socket.IPPROTO_IP
sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
sniffer.bind((host, 0))
# we want the IP headers included in the capture
#sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
while True:
packet = sniffer.recvfrom(65565)
#packet string from tuple
packet = packet[0]
#take first 20 characters for the ip header
ip_header = packet[0:20]
#now unpack them :)
iph = unpack('!BBHHHBBH4s4s' , ip_header)
version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xF
iph_length = ihl * 4
total_len = iph[2]
ttl = iph[5]
protocol = iph[6]
s_addr = socket.inet_ntoa(iph[8]);
d_addr = socket.inet_ntoa(iph[9]);
if protocol == 6:
print 'Length : ' + str(total_len) + ' Source Address : ' + str(s_addr) + ' Destination Address : ' + str(d_addr)
很奇怪,我对C ++代码有什么错误吗?