linux C监听本地所有数据包

char buffer[8196];

void listen_all_package(){

int sock, n;

char *ifname = "eth0";

struct sockaddr_ll addr;

if ((sock=socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)))<0) 
{
return FALSE;
}
memset(&addr, 0, sizeof(addr));

addr.sll_family=AF_PACKET;
addr.sll_protocol=htons(ETH_P_ALL);
addr.sll_ifindex=0;

if ((bind(sock, (struct sockaddr*)&addr, sizeof(addr)))<0) 
{
return FALSE;
}

//设置混杂模式

struct ifreq ethreq;

strncpy(ethreq.ifr_name,ifname ,IFNAMSIZ);

if (ioctl(sock,SIOCGIFFLAGS,ðreq)==-1) 
{
return FALSE;
}
ethreq.ifr_flags|=IFF_PROMISC;
if (ioctl(sock,SIOCSIFFLAGS,ðreq)==-1) 
{
return FALSE;
}

while(1){

n = recvfrom(sock,buffer,sizeof(buffer),0,NULL,NULL);

...

}


}





你可能感兴趣的:(TCPIP网络协议,linux,socket编程)