I m 沿用这一C应用范例,即:
https://www.binarytides.com/ Packet-sniffer-code-c-linux/。
除我外,在编造袖珍片后,将袖珍材料加在一起:
const std::string& iff = "wlp3s0";
int r = setsockopt(sock_raw, SOL_SOCKET, SO_BINDTODEVICE, iff.c_str(), iff.length());
if (r == -1)
{
std::abort();
}
然后我离开申请:
sudo ./the_app
我打开了电线,并听听了Wlp3s0无线界面。 我从捕获中删除了电离网接口。
之后,我操作了<代码>sudo dhclient -r和sudo dhclient
,以阻止/启动DHCP和Rshark探测器4或5 DHCP 包装。
However, the C raw socket sniffer shows absolutely no UDP packets received.
如果我接着打开一个网络浏览器,它就开始展示TCP包装(Wireshark报告DHCP包装是UDP)。
What s happening? I m using Ubuntu 22.04
缩略语:
#include<stdio.h> //For standard things
#include<stdlib.h> //malloc
#include<string.h> //memset
#include<netinet/ip_icmp.h> //Provides declarations for icmp header
#include<netinet/udp.h> //Provides declarations for udp header
#include<netinet/tcp.h> //Provides declarations for tcp header
#include<netinet/ip.h> //Provides declarations for ip header
#include<sys/socket.h>
#include<arpa/inet.h>
#include <unistd.h>
void ProcessPacket(unsigned char* , int);
int tcp=0,udp=0,icmp=0,others=0,igmp=0,total=0,i,j;
struct sockaddr_in source,dest;
int main()
{
unsigned char *buffer = (unsigned char *)malloc(65536); //Its Big!
printf("Starting...
");
int sock_raw = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
if(sock_raw < 0)
{
std::abort();
}
int r = setsockopt(sock_raw, SOL_SOCKET, SO_BINDTODEVICE, "wlp3s0", strlen("wlp3s0"));
if (r == -1)
{
std::abort();
}
while(1)
{
int data_size = recv(sock_raw , buffer , 65536 , 0);
if(data_size <0 )
{
std::abort();
}
ProcessPacket(buffer , data_size);
}
::close(sock_raw);
return 0;
}
void ProcessPacket(unsigned char* buffer, int size)
{
//Get the IP Header part of this packet
struct iphdr *iph = (struct iphdr*)buffer;
++total;
switch (iph->protocol) //Check the Protocol and do accordingly...
{
case 1: //ICMP Protocol
++icmp;
//print_icmp_packet(buffer, size);
break;
case 2: //IGMP Protocol
++igmp;
break;
case 6: //TCP Protocol
++tcp;
//print_tcp_packet(buffer , size);
break;
case 17: //UDP Protocol
++udp;
//print_udp_packet(buffer , size);
break;
default: //Some Other Protocol like ARP etc.
++others;
break;
}
printf("TCP : %d UDP : %d ICMP : %d IGMP : %d Others : %d Total : %d
",tcp,udp,icmp,igmp,others,total);
}