1 Star 0 Fork 0

fly / tcpip

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
arpdump.cpp 1.82 KB
一键复制 编辑 原始数据 按行查看 历史
fly 提交于 2023-03-01 21:04 . arpdump
#include <arpa/inet.h>
#include <iostream>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/if_packet.h>
#include <net/ethernet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
using namespace std;
struct eth_addr {
unsigned char addr[6];
};
struct __attribute__((__packed__)) myarp {
struct ethhdr eth_hdr;
struct arphdr arp_hdr;
struct eth_addr sender_ha;
struct in_addr sender_ip;
struct eth_addr target_ha;
struct in_addr target_ip;
};
ostream &operator<<(ostream &out, const struct in_addr &ip)
{
out << inet_ntoa(ip);
return out;
}
ostream &operator<<(ostream &out, const struct eth_addr &eth)
{
char buf[32];
sprintf(buf, "%02x:%02x:%02x:%02x:%02x:%02x",
eth.addr[0], eth.addr[1], eth.addr[2], eth.addr[3], eth.addr[4], eth.addr[5]);
out << buf;
return out;
}
ostream &operator<<(ostream &out, const struct myarp &arp)
{
if (ntohs(arp.arp_hdr.ar_op) == ARPOP_REQUEST)
out << "Request: who-has " << arp.target_ip << " tell " << arp.sender_ip;
else if (ntohs(arp.arp_hdr.ar_op) == ARPOP_REPLY)
out << "Reply: " << arp.sender_ip << " is-at " << arp.sender_ha;
return out;
}
void dump(const unsigned char *ptr, ssize_t len)
{
struct myarp *arp = (struct myarp *)ptr;
if (ntohs(arp->eth_hdr.h_proto) != ETH_P_ARP)
return;
cout << *arp << endl;
}
int main(int argc, char *argv[])
{
int sockfd;
ssize_t nrecv;
unsigned char buf[1024];
sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sockfd < 0) {
perror("socket");
exit(1);
}
for (;;) {
nrecv = recvfrom(sockfd, buf, sizeof(buf), 0, NULL, NULL);
if (nrecv < 0) {
perror("socket");
exit(1);
}
dump(buf, nrecv);
}
}
C++
1
https://gitee.com/q723937936/tcpip.git
git@gitee.com:q723937936/tcpip.git
q723937936
tcpip
tcpip
master

搜索帮助