3,846
社区成员
发帖
与我相关
我的任务
分享
int main(int argc, char ** argv)
{
struct ifreq ethreq; /* 网络接口结构 */
char ef[ETH_FRAME_LEN]; /*以太帧缓冲区*/
struct ethhdr *p_ethhdr; /*以太网头部指针*/
int n,i;
struct iphdr *p_iphdr;
struct udphdr *p_udphdr;
unsigned char *pucTemp1,*pucTemp2;
char *app_data = NULL; /*应用数据指针*/
int app_len = 0; /*应用数据长度*/
char *UDP_data[2048];
struct sigaction sighandle;
/* 信号设置 */
sighandle.sa_flags = 0;
sighandle.sa_handler = sig_handler;
sigemptyset(&sighandle.sa_mask);
sigaction(SIGTERM, &sighandle, NULL);
sigaction(SIGINT, &sighandle, NULL);
sigaction(SIGQUIT, &sighandle, NULL);
/* 打开套接字 */
if((fd = socket(AF_PACKET, SOCK_RAW, htons(0x0003))) == -1)
{
perror("socket");
exit(1);
}
/* 设置网卡为混杂模式,抓取所有数据 */
strncpy(ethreq.ifr_name, "eth0", IFNAMSIZ);
if(ioctl(fd, SIOCGIFFLAGS, ðreq) == -1)
{
perror("ioctl");
close(fd);
exit(1);
}
ethreq.ifr_flags |= IFF_PROMISC;
if(ioctl(fd, SIOCSIFFLAGS, ðreq) == -1)
{
perror("ioctl");
close(fd);
exit(1);
}
while(1)
{
/*初始化变量*/
memset(ef,0x0,sizeof(ef));
p_ethhdr = NULL;
p_iphdr = NULL;
p_udphdr = NULL;
app_data = NULL;
app_len = 0;
/*从套接口读取链路层的方法*/
p_ethhdr = (struct ethhdr*)ef; /*使p_ethhdr指向以太网帧的帧头*/
/*读取以太网数据,n为返回的实际捕获的以太帧的帧长*/
n = read(fd, ef, ETH_FRAME_LEN);
printf("length:[%u][%s]\n",n,ef);
/*打印IP报文的源IP地址和目的IP地址,由于ip包包含TCP数据包和UDP数据包*/
if(ntohs(p_ethhdr->h_proto)==0x0800) /*0x0800:IP包*/
{
/*定位IP头部*/
p_iphdr = (struct iphdr*) (ef + ETH_HLEN);
/*打印UDP报文的源端口值和目的端口值*/
if(p_iphdr->protocol==17)
{
/*取得UDP报头*/
p_udphdr = (struct udphdr*)(p_iphdr+p_iphdr->ihl*4);
/*获得UDP协议部分的应用数据地址*/
app_data = (char*)(p_udphdr + p_udphdr->len);
/*获得UDP协议部分的应用数据长度*/
app_len = n - 16 - p_iphdr->ihl*4 - p_udphdr->len;
}
}
}
close(fd);
exit(0);
}