sniffer in linux by raw way(not pcap)Linux 混杂模式sniff

在嵌入式上探测GPRS,Ethernet的报文,由于系统是裁剪过的,少了很多库,所以Tcpdump是用不了了,只好自己改了个,代码如下:

 

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <linux/types.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <sys/socket.h> #include <unistd.h> #include <net/if.h> #include <sys/ioctl.h> #include <netinet/if_ether.h> // /* * set the interface to promisc mode. */ int set_netpromisc(char* interface) { int fd, s; struct ifreq ifr; fd = socket(AF_INET, SOCK_PACKET, htons(0x800)); if (fd < 0) { perror("can not get SOCK_PACKET socket"); return 0; } printf("sniffer in interface=%s...../n/n/n", interface); strcpy(ifr.ifr_name, interface); s = ioctl(fd, SIOCGIFFLAGS, &ifr); if (s < 0) { close(fd); perror("can not get flags"); return 0; } ifr.ifr_flags |= IFF_PROMISC; s = ioctl(fd, SIOCSIFFLAGS, &ifr); if (s < 0) { close(fd); perror("can not set flags"); return 0; } return fd; } /* * display characters */ void show_char(void *buff, int len) { while (len --) { if (buff) { printf("%c", *((char *)(buff++))); } else { printf("."); buff ++; } } } /* * display a buff in Hex. */ void show_hex(void *buff, int len) { int i = 15, tmp; while (len --) { printf("%02x ", *(unsigned char *)(buff ++)); if (i -- == 0) { printf("/t"); show_char(buff - 16, 16); printf("/n"); i = 15; } } if (i != 0) { tmp = i + 1; while (tmp --) printf(" %c ", '.'); printf("/t"); show_char(buff - 15 + i, 16 - i); printf("/n"); } printf("/n/n"); } /* * the main function. */ int main(int argc,char *argv[]) { int sockfd, ret; char buff[4096]; int type = ETH_P_IP; char* interface = "eth0"; if (argc > 1) { interface = argv[1]; } set_netpromisc(interface); if (argc > 2 && strncmp(argv[2], "all", 3) == 0) { type = ETH_P_ALL; } else { type = ETH_P_IP; } //if((sockfd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL))) == -1) if((sockfd = socket(PF_INET, SOCK_PACKET, htons(type))) == -1) // if((sockfd = socket(AF_INET, SOCK_PACKET, IPPROTO_TCP)) == -1) { perror("socket error"); return 0; } memset(buff, 0x00, 4096); /* * recvfrom all the packages. */ while ((ret = recvfrom(sockfd, buff, 4096, 0, NULL, NULL)) > 0) { show_hex(buff, ret); // display it now.. memset(buff, 0x00, ret); } close(sockfd); return 0; }

也可先在终端上运行:

ifconfig eth0 -promisc

ifconfig ppp0 -promisc


将网卡设置成混杂模式.这样程序里就不必调用set_netpromisc这个函数了,

你可能感兴趣的:(sniffer in linux by raw way(not pcap)Linux 混杂模式sniff)