<!-- google_ad_client = "pub-2416224910262877"; google_ad_width = 728; google_ad_height = 90; google_ad_format = "728x90_as"; google_ad_channel = ""; google_color_border = "E1771E"; google_color_bg = "FFFFFF"; google_color_link = "0000FF"; google_color_text = "000000"; google_color_url = "008000"; // -->
这两天在linux服务器上利用原始套接字搞了一个数据包监听转发工具,其中的关键代码摘抄如下:
...
m_sockid=::socket(PF_PACKET, SOCK_RAW,0);
if(m_sockid==INVALID_SOCKET)return false;
struct sockaddr_ll sll;
struct ifreq ifr;
sll.sll_family = AF_PACKET;
sll.sll_protocol = htons(ETH_P_IP);
if(dip!=INADDR_ANY)
{
for(int i=0;i<100;i++)
{
sprintf(ifr.ifr_name,"eth%d",i);
if(ioctl(m_sockid,SIOCGIFADDR,&ifr)<0)
{
::close(m_sockid);
return false;
}
if(((sockaddr_in*)&ifr.ifr_addr)->sin_addr.s_addr==dip)//dip是需要绑定的网卡地址
{
ioctl(m_sockid,SIOCGIFINDEX,&ifr);
sll.sll_ifindex = ifr.ifr_ifindex;
break;
}
}
}
else
{
sll.sll_ifindex = 0; //接收全部网卡数据包
}
if(::bind(m_sockid, (sockaddr *)&sll, sizeof(sockaddr_ll))!=0)//绑定网卡
{
::close(m_sockid);
return false;
}
else
{
return true;
}
...
如上,便建立了一个可以收听特定网卡全部ip数据包的原始套接字,其他略。
其他文章:
<!-- google_ad_client = "pub-2416224910262877"; google_ad_width = 728; google_ad_height = 90; google_ad_format = "728x90_as"; google_ad_channel = ""; google_color_border = "E1771E"; google_color_bg = "FFFFFF"; google_color_link = "0000FF"; google_color_text = "000000"; google_color_url = "008000"; // -->