Linux下C/C++中的数据包嗅探器

Dir*_*irk 2 c c++ sockets linux raw-sockets

我尝试在 linux 下使用原始套接字捕获网络数据包。
这有时有效。似乎我可以捕捉到一些对话,但不是全部。

我创建了一个套接字:

sock = socket( PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));  
Run Code Online (Sandbox Code Playgroud)

然后我通过以下方式将其绑定到 eth0:

struct sockaddr_ll sll;
struct ifreq ifr;

memset( &sll, 0, sizeof( sll));
memset( &ifr, 0, sizeof( ifr));

strcpy( ifr.ifr_name, "eth0");

if(( ioctl( sock, SIOCGIFINDEX, &ifr))==-1)
{
   printf( "error\n");
   return(-1);
}
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
sll.sll_protocol = htons( ETH_P_ALL);

bind( sock, (struct sockaddr*)&sll, sizeof( sll));
Run Code Online (Sandbox Code Playgroud)

然后我尝试接收:

int packetsize = 65535;
char packet[packetsize];

struct ether_header *eth = (struct ether_header *) packet;
struct iphdr *ip = (struct iphdr *) (packet + sizeof(struct ether_header));

struct tcphdr *tcp = (struct tcphdr*) (packet+sizeof( struct ether_header)+sizeof( struct iphdr));
struct udphdr *udp = (struct udphdr*) (packet+sizeof( struct ether_header)+sizeof( struct iphdr));



int k;

while(1)
{
    k = read( sock, packet, sizeof( packet));

    if( k>0)
    {
        if( ntohs( eth-> ether_type) == 0x0800)
        {       
            inet_ntop( AF_INET, &ip->saddr, source, 16);
            inet_ntop( AF_INET, &ip->daddr, dest, 16);

            switch (ip->protocol)
            {
            case 6://TCP
                printf( "TCP: %s:%d -> %s:%d\n", source, ntohs( tcp->source), dest, ntohs( tcp->dest));
                break;
            case 17://UDP
                printf( "UDP: %s:%d -> %s:%d\n", source, ntohs( udp->source), dest, ntohs( udp->dest));
                break;
            default:
                break;
            }//switch           
        }// if 0x800    
    }//if( k>0)
}//while
Run Code Online (Sandbox Code Playgroud)

我可以捕获网络中的一些数据包,但不是全部。似乎我错过了两方之间的整个对话。

有谁知道我做错了什么?

提前致谢

短剑

abl*_*igh 5

除非这是某种家庭作业练习或受虐练习,否则我强烈建议您使用libpcapwhich 将提供一种便携式方法来解决这个已经过测试的问题。libpcap是什么tcpdumpwireshark在引擎盖下使用。