inet_ntoa转换问题

时间:2011-07-08 07:58:29

标签: c

在这段代码中,我捕获了数据包,我试图通过使用inet_ntoa显示源和目标地址,甚至在此之前我正在以hexa格式打印数据包src和dst地址。这里的问题是两者都不匹配,inet_ntoa的o / p错误,如o / p所示

  the src ip address should be 172.28.6.87 but inet_ntoa shows 86.212.172.28
  the src ip address should be 172.28.6.110 but inet_ntoa shows 6.87.172.28


  char *ptr = NULL;
  ptr_fltr = (struct packet_filter*)(packet); 
  memcpy(out_data,packet,50);
  printf("\n");
  for(i= 28;i<36;i++)
  printf("%#x\t",out_data[i]);
  printf("*******************************************************************\n");
  printf("---------------------Received Packet Info--------------------\n");
  ptr = inet_ntoa(ptr_fltr->ip.ip_src);
  printf("Source Ip Addr :%s\n",ptr);

这里

 struct packet_filter
  {
    struct mac_filter mac;
    struct ip_filter ip;
    union {
            struct udp_filter proto;
    }protocol;
  }__attribute__((packed));


 struct ip_filter
 {
    u_char ip_vhl;
    u_char ip_tos; /* type of service */
    u_short ip_len; /* total length */
    u_short ip_id; /* identification */
    u_short ip_off; /* fragment offset field */
    u_char ip_ttl; /* time to live */
    u_char ip_p; /* protocol */
    u_short ip_sum; /* checksum */
    struct in_addr ip_src; /* source and dest address */
    struct in_addr ip_dst; /* source and dest address */
 }__attribute__((packed));

输出

  0xac    0x1c    0x6 0x57    0xac    0x1c    0x6 0x6e         
  ************************************************************
  --------------------Received Packet Info--------------------
  Source Ip Addr :86.212.172.28
  Destination Ip Addr :6.87.172.28

2 个答案:

答案 0 :(得分:2)

显然,当你到达IP地址时,你的结构会被两个字节关闭。我已经检查过IPv4协议,那个位看起来还不行。所以我怀疑struct mac是错的。我认为struct mac是一个以太网框架。如果是这样,它已经有点可疑了,因为Ethernet frame不是固定长度。

此外,(假设您从Berkeley Packet Filter获取这些内容)确保从bpf标头正确计算数据包的开头(您不能依赖sizeof(struct bpf_header))。

答案 1 :(得分:0)

您的IP数据包从偏移量16开始,如果您从以太网标头复制 struct mac ,则它长度为14个字节。看起来数据包中有一些意外的数据。