悲剧是怎么炼成的

晚上写了一个简单的Sniffer,  发现报错 ( 无效的参数 )。

怀疑是平台不兼容的问题,四处找答案,从读源码到Google,  从晚上折腾到早上,最后发现是:

if ( sock = Socket() < 0 )

原先还在纳闷socket怎么会返回0, 看了书上 socket()错误会返回-1 就没怎么在意了。

早上仔细一看原来自己真的2了,经常在Blog里面说的,比较的优先级大于赋值,最后还是忘记了,哎。

杯具啊。

既然来说了,顺便贴一下代码吧。

  1
  2 #include 
  3 #include 
  4 #include 
  5 #include 
  6 #include 
  7 #include 
  8 #include 
  9 #include 
 10 #include 
 11 #include 
 12 #include 
 13 #include 
 14 #include 
 15 #include 
 16 #include 
 17 #include 
 18 #include 
 19 //#include 
 20
 21 #define INTERFACE "eth2"
 22
 23 typedef struct sockaddr SA;
 24
 25
 26 int Set_Promisc(char * interface, int sock)
 27 {
 28
 29     struct ifreq ifr;
 30
 31     strncpy(ifr.ifr_name, interface, strlen(interface) + 1);
 32
 33 //  ifr.ifr_addr.sa_family = AF_INET;
 34
 35     printf("\n%d, %s, %s\n", sock, interface, ifr.ifr_name);
 36
 37     if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
 38     {
 39
 40         printf("Could not retreive flags for the interface: %s \n", strerror(errno));
 41         exit(0);
 42     }
 43
 44     printf("The interface is ::: %s \n", interface);
 45
 46     perror("Retrieved flags form interface successfully.");
 47
 48     ifr.ifr_flags |= IFF_PROMISC;
 49
 50     if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
 51     {
 52         perror("Could not set the PROMISC flag.\n");
 53         exit(0);
 54     }
 55
 56     printf("Setting interface ::: %s ::: to promisc", interface);
 57
 58     return 0;
 59 }
 60
 61 int main()
 62 {
 63     int sock, bytes_recevied, fromlen;
 64     char buffer[65536];
 65
 66     struct sockaddr_in from;
 67     struct ip * ip;
 68     struct tcphdr * tcp;
 69
 70     if ((sock = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) < 0)
 71     {
 72         perror("The raw socket was not created.");
 73         exit(0);
 74     }
 75
 76     Set_Promisc(INTERFACE, sock);
 77
 78     while (1)
 79     {
 80         fromlen = sizeof(from);
 81
 82         bytes_recevied = recvfrom(sock, buffer, sizeof(buffer), 0, (SA *)&from, &fromlen);
 83
 84         printf("\nBytes recevied ::: %5d\n", bytes_recevied);
 85
 86         printf("Source address ::: %s\n", (char *)inet_ntoa(from.sin_addr));
 87
 88         ip = (struct ip *) buffer;
 89
 90         if (ip->ip_p == 6) {
 91
 92             printf("IP header length ::: %d \n", ip->ip_hl);
 93
 94             printf("Protocol ::: %d\n", ip->ip_p);
 95
 96             tcp = (struct tcphdr *)(buffer + (4 * ip->ip_p));
 97
 98             printf("Source port ::: %d \n", ntohs(tcp->source));
 99
100             printf("Dest prot ::: %d \n", ntohs(tcp->dest));
101         }
102     }
103     return 0;
104 }

此条目发表在C, Linux, 唠叨, 编程分类目录,贴了, 标签。将固定链接加入收藏夹。

发表评论

邮箱地址不会被公开。 必填项已用*标注