ntohs()问题

时间:2011-11-24 18:41:27

标签: c byte host

此程序应从脱机转储文件中捕获数据包并对其进行解码。这里我遇到了ntohs()函数的问题(它接近结束,头文件描述在开头)。为什么它不起作用? OS win7 x86,VS 2010 express。

#include "pcap.h"

#define SIZE_ETHERNET 14
#define ETHER_ADDR_LEN  6
/* 4 bytes IP address */
typedef struct ip_address{
    u_char byte1;
    u_char byte2;
    u_char byte3;
    u_char byte4;
}ip_address;

/* IPv4 header */
typedef struct ip_header{
    u_char  ver_ihl;        // Version (4 bits) + Internet header length (4 bits)
    u_char  tos;            // Type of service 
    u_short tlen;           // Total length 
    u_short identification; // Identification
    u_short flags_fo;       // Flags (3 bits) + Fragment offset (13 bits)
    u_char  ttl;            // Time to live
    u_char  proto;          // Protocol
    u_short crc;            // Header checksum
    ip_address  saddr;      // Source address
    ip_address  daddr;      // Destination address
    u_int   op_pad;         // Option + Padding
}ip_header;

/* UDP header*/
typedef struct udp_header{
    u_short sport;          // Source port
    u_short dport;          // Destination port
    u_short len;            // Datagram length
    u_short crc;            // Checksum
}udp_header;


typedef struct ethernet_address{
    u_char byte1;
    u_char byte2;
    u_char byte3;
    u_char byte4;
    u_char byte5;
    u_char byte6;
}ethernet_address;

    /* Ethernet header */
typedef struct ethernet_header {
        ethernet_address ether_dhost; /* Destination host address */
        ethernet_address ether_shost; /* Source host address */
        u_short ether_type; /* IP? ARP? RARP? etc */
    };

/* TCP header */
typedef struct tcp_header {
        u_short th_sport;   /* source port */
        u_short th_dport;   /* destination port */

        u_char th_offx2;    /* data offset, rsvd */
    #define TH_OFF(th)  (((th)->th_offx2 & 0xf0) >> 4)
        u_char th_flags;
    #define TH_FIN 0x01
    #define TH_SYN 0x02
    #define TH_RST 0x04
    #define TH_PUSH 0x08
    #define TH_ACK 0x10
    #define TH_URG 0x20
    #define TH_ECE 0x40
    #define TH_CWR 0x80
    #define TH_FLAGS (TH_FIN|TH_SYN|TH_RST|TH_ACK|TH_URG|TH_ECE|TH_CWR)
        u_short th_win;     /* window */
        u_short th_sum;     /* checksum */
        u_short th_urp;     /* urgent pointer */
}tcp_header;

/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
/* Packet count */
int num = 1;

int main(int argc, char **argv)
{
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
char source[PCAP_BUF_SIZE];
u_int netmask;
char packet_filter[] = "";
struct bpf_program fcode;

    if(argc != 2){

        printf("usage: %s filename", argv[0]);
        return -1;

    }

    /* Create the source string according to the new WinPcap syntax */
    if ( pcap_createsrcstr( source,         // variable that will keep the source string
                            PCAP_SRC_FILE,  // we want to open a file
                            NULL,           // remote host
                            NULL,           // port on the remote host
                            argv[1],        // name of the file we want to open
                            errbuf          // error buffer
                            ) != 0)
    {
        fprintf(stderr,"\nError creating a source string\n");
        return -1;
    }

    /* Open the adapter */
    if ( (adhandle= pcap_open(source,  // name of the device
                             65536,     // portion of the packet to capture. 
                                        // 65536 grants that the whole packet will be captured on all the MACs.
                             PCAP_OPENFLAG_PROMISCUOUS,         // promiscuous mode
                             1000,      // read timeout
                             NULL,      // remote authentication
                             errbuf     // error buffer
                             ) ) == NULL)
    {
        fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n");
        return -1;
    }

    /* Check the link layer. We support only Ethernet for simplicity. */
    if(pcap_datalink(adhandle) != DLT_EN10MB)
    {
        fprintf(stderr,"\nThis program works only on Ethernet networks.\n");
        return -1;
    }

  /*  if(d->addresses != NULL)
         Retrieve the mask of the first address of the interface 
        netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
    else */
        /* If the interface is without addresses we suppose to be in a C class network */
        netmask=0xffffff; 


    //compile the filter
    if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0 )
    {
        fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
        return -1;
    }

    //set the filter
    if (pcap_setfilter(adhandle, &fcode)<0)
    {
        fprintf(stderr,"\nError setting the filter.\n");
        return -1;
    }

    /* start the capture */
    pcap_loop(adhandle, 0, packet_handler, NULL);

    return 0;
}

/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
    struct tm ltime;
    char timestr[16];
    time_t local_tv_sec;
    u_int ip_len;
    u_short sport,dport;
    ip_header *ih;
    const struct ethernet_header *ethh; /* The ethernet header */


    /*
     * Unused variable
     */
    (VOID)(param);

    printf("Packet %d\n", num);
    num++;

    /* convert the timestamp to readable format */
    local_tv_sec = header->ts.tv_sec;
    localtime_s(&ltime, &local_tv_sec);
    strftime( timestr, sizeof timestr, "%H:%M:%S", &ltime);

    /* print timestamp and length of the packet */
 //   printf("%s.%.6d len:%d ", timestr, header->ts.tv_usec, header->len);

    /* retireve the position of the ethernet header */
    ethh = (struct ethernet_header*)(pkt_data);
    /* retireve the position of the ip header */
    ih = (ip_header *) (pkt_data + 14); //length of ethernet header

    /* retireve the position of the udp header */
    ip_len = (ih->ver_ihl & 0xf) * 4;

    /* print ip addresses and ports */
    printf("Eth Src: %x:%x:%x:%x:%x:%x >>> Dest: %x:%x:%x:%x:%x:%x\nIP Src: %d.%d.%d.%d >>> Dest: %d.%d.%d.%d\n",
        ethh->ether_shost.byte1,
        ethh->ether_shost.byte2,
        ethh->ether_shost.byte3,
        ethh->ether_shost.byte4,
        ethh->ether_shost.byte5,
        ethh->ether_shost.byte6,
        ethh->ether_dhost.byte1,
        ethh->ether_dhost.byte2,
        ethh->ether_dhost.byte3,
        ethh->ether_dhost.byte4,
        ethh->ether_dhost.byte5,
        ethh->ether_dhost.byte6,
        ih->saddr.byte1,
        ih->saddr.byte2,
        ih->saddr.byte3,
        ih->saddr.byte4,
        ih->daddr.byte1,
        ih->daddr.byte2,
        ih->daddr.byte3,
        ih->daddr.byte4
        );
    /* Panage protocols */
    if(ih->proto == 0x11)
        {
            udp_header *uh;
            uh = (udp_header *) ((u_char*)ih + ip_len);
            printf("UDP Src: %d >>> Dest: %d\n", uh->sport,uh->dport);
        }
    else if(ih->proto == 0x06)
        {
            tcp_header *tcp = NULL;
                /* convert from network byte order to host byte order */
            tcp = (tcp_header *) ((u_char*)ih + ip_len);
/*HERE*/            sport = ntohs(tcp->th_sport);
/*HERE*/        dport = ntohs(tcp->th_dport);
            printf("TCP Src: %d >>> Dest: %d\n", sport,dport);
        }
}

错误日志:

1>------ Build started: Project: cw1, Configuration: Debug Win32 ------
1>  cw1.c
1>cw1.obj : error LNK2019: unresolved external symbol __imp__ntohs@4 referenced in function _packet_handler
1>C:\Users\Medardas\Desktop\ComputerScience\C.SC251 - CW1\cw1\Debug\cw1.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

2 个答案:

答案 0 :(得分:1)

尝试添加<arpa/inet.h><netinet/in.h>。如果做不到这一点,请检查链接器设置。

答案 1 :(得分:0)

这是一个链接器错误。咨询documentation of the function。在该页面的底部(所有这些页面都以相同的方式布局),您将找到所需的头,lib和DLL的详细信息。在这种情况下,您需要链接Ws2_32.lib