- 论坛徽章:
- 0
|
/************************sniffer.c****************************/
#include <stdio.h>;
#include <stdlib.h>;
#include <unistd.h>;
#include <string.h>;
#include <signal.h>;
#include <netinet/in.h>;
#include <netinet/ip.h>;
#include <netinet/tcp.h>;
#include <net/if.h>;
#include <netdb.h>;
#include <sys/ioctl.h>;
#include <sys/stat.h>;
#include <fcntl.h>;
#include <ctype.h>;
#include <sys/file.h>;
#include <sys/time.h>;
#include <sys/socket.h>;
#include <arpa/inet.h>;
#include <netinet/if_ether.h>;
#define INTERFACE "eth0" /* 网卡 */
int set_promisc(char *interface,int sock) /* 杂乱模式 */
{
struct ifreq ifr;
strncpy(ifr.ifr_name, interface,strlen(interface)+1);
if((ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)) {
printf("Could not receive flags for the interface\n" ;
exit(0);
}
ifr.ifr_flags |= IFF_PROMISC;
if(ioctl(sock, SIOCSIFFLAGS, &ifr) == -1 ) {
printf("Could not set the PROMISC flag.\n" ;
exit(0);
}
printf("Setting interface ::: %s ::: to promisc\n", interface);
}
main()
{
int sock,bytes_received,len;
char *data;
char buffer[65535];
struct sockaddr_in addr;
struct iphdr *ip;
struct tcphdr *tcp;
if((sock = socket(AF_INET,SOCK_RAW,IPPROTO_TCP)) == -1)
{ /* 使用SOCK_RAW */
printf("sniffer failt\n" ;
exit(0);
}
set_promisc(INTERFACE,sock);
while(1)
{
len = sizeof(addr);
bytes_received = recvfrom(sock,(char *)buffer,sizeof(buffer),0,(struct sockaddr *)&addr,&len);
printf("\nBytes received %5d\n",bytes_received);
printf("Source address %s \n",inet_ntoa(addr.sin_addr));
ip = (struct iphdr *)buffer; /* 格式化buffer的内容 */
printf("IP header length %d\n",ip->;tot_len);
printf(" rotocol %d\n",ip->;protocol);
tcp = (struct tcphdr *)(buffer+sizeof(struct iphdr)); /* 格式化ip数据后面的buffer内容 */
printf("Source port %d\n",ntohs(tcp->;source));
printf("Dest port %d \n",ntohs(tcp->;dest));
data = &buffer[sizeof(struct iphdr) + sizeof(struct tcphdr)]; /* data 等于去掉iphdr和tcphdr后的buffer内容 */
printf("data: %s",data);
}
}
/*************************************************************************/
编译运行了以后似乎不可以抓取所有通过本机网卡的数据包,只显示目的地址是本机的数据包。数据data显示不正常,看不到应该有的数据,ip头的长度有1万多字节,正常吗?本来一个很简单的程序有这么多问题能帮我看看吗?
希望能得到你们的帮助,谢谢。 |
|