linux进去网卡,Linux上使用socket进行网卡抓包

Linux下使用socket进行网卡抓包

有时候需要自己编写代码进行抓包,以找出特殊意义的包。

下面是简单的一个示例:

#include

#include

#include

#include

#include

#include

#include

int main (int argc, char *argv[])

{

int sockfd;

int ret = 0;

char buffer[1518] = {0};

char *eth_head = NULL;

/* PF_PACKET:链路层,  SOCK_RAW: 包含 mac头, ETH_P_ALL: 所有协议  */

if ((sockfd = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL))) < 0)

{

printf ("create socket failed\n");

return -1;

}

while (1)

{

memset (buffer, 0x0, sizeof (buffer));

ret = recvfrom (sockfd, buffer, sizeof (buffer), 0, NULL, NULL);

printf ("recview package length : %d\n", ret);

eth_head = buffer;

printf ("PACKAGE START\n");

/* get source and dectination mac address */

printf ("dectination mac:%02x-%02x-%02x-%02x-%02x-%02x,"

"source mac:%02x-%02x-%02x-%02x-%02x-%02x;\n", eth_head[0],

eth_head[1], eth_head[2], eth_head[3], eth_head[4],

eth_head[5], eth_head[6], eth_head[7], eth_head[8],

eth_head[9], eth_head[10], eth_head[11]);

printf ("eth_type:%02x%02x\n", eth_head[12], eth_head[13]);

/* ARP proptocol flag */

if (0x08 == eth_head[12] && 0x06 == eth_head[13])

{

printf ("ARP source ip:%d.%d.%d.%d,destination ip:%d.%d.%d.%d;\n",

eth_head[28], eth_head[29], eth_head[30], eth_head[31],

eth_head[38], eth_head[39], eth_head[40], eth_head[41]);

}

/* IPv4 proptocol flag */

else if (0x08 == eth_head[12] && 0x00 == eth_head[13])

{

if (0x45 == eth_head[14])

{

printf ("IPv4 source ip:%d.%d.%d.%d,destination ip:%d.%d.%d."

"%d;\n", eth_head[26], eth_head[27], eth_head[28],

eth_head[29], eth_head[30], eth_head[31],

eth_head[32], eth_head[33]);

}

else

{

printf ("p_head:%02x\n", eth_head[14]);

}

}

printf ("PACKAGE END\n");

}

return 0;

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值