Поиск:

Ответ в темуСоздание новой темы Создание опроса
> wpcap error, ошибка при компиляции 
:(
    Опции темы
criz
Дата 30.9.2008, 17:18 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 63
Регистрация: 13.2.2008

Репутация: нет
Всего: нет



Здравствуйте, ув. форумчане! smile
Пытаюсь подружить С++ Билдер с Wpcap'ом. Не получается. Выдает ошибки при компиляции.
Конвертировал wpcap.lib и packet.lib, с помощью coff2omf.exe, закинул в Include\.
Вот исходник:
Код

#include "pcap/pcap.h"

/* 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;

/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);


main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
u_int netmask;
char packet_filter[] = "ip and udp";
struct bpf_program fcode;

    /* Retrieve the device list */
    if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
    {
        fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
        exit(1);
    }

    /* Print the list */
    for(d=alldevs; d; d=d->next)
    {
        printf("%d. %s", ++i, d->name);
        if (d->description)
            printf(" (%s)\n", d->description);
        else
            printf(" (No description available)\n");
    }

    if(i==0)
    {
        printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
        return -1;
    }
    
    printf("Enter the interface number (1-%d):",i);
    scanf("%d", &inum);
    
    if(inum < 1 || inum > i)
    {
        printf("\nInterface number out of range.\n");
        /* Free the device list */
        pcap_freealldevs(alldevs);
        return -1;
    }

    /* Jump to the selected adapter */
    for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
    
    /* Open the adapter */
    if ( (adhandle= pcap_open(d->name,    // 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");
        /* Free the device list */
        pcap_freealldevs(alldevs);
        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");
        /* Free the device list */
        pcap_freealldevs(alldevs);
        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");
        /* Free the device list */
        pcap_freealldevs(alldevs);
        return -1;
    }
    
    //set the filter
    if (pcap_setfilter(adhandle, &fcode)<0)
    {
        fprintf(stderr,"\nError setting the filter.\n");
        /* Free the device list */
        pcap_freealldevs(alldevs);
        return -1;
    }
    
    printf("\nlistening on %s...\n", d->description);
    
    /* At this point, we don't need any more the device list. Free it */
    pcap_freealldevs(alldevs);
    
    /* 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];
    ip_header *ih;
    udp_header *uh;
    u_int ip_len;
    u_short sport,dport;
    time_t local_tv_sec;

    /* convert the timestamp to readable format */
    local_tv_sec = header->ts.tv_sec;
    ltime=localtime(&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 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;
    uh = (udp_header *) ((u_char*)ih + ip_len);

    /* convert from network byte order to host byte order */
    sport = ntohs( uh->sport );
    dport = ntohs( uh->dport );

    /* print ip addresses and udp ports */
    printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d\n",
        ih->saddr.byte1,
        ih->saddr.byte2,
        ih->saddr.byte3,
        ih->saddr.byte4,
        sport,
        ih->daddr.byte1,
        ih->daddr.byte2,
        ih->daddr.byte3,
        ih->daddr.byte4,
        dport);
}

 Результат компиляции:
Код

[C++ Error] pcap-bpf.h(68): E2257 , expected
[C++ Error] pcap-bpf.h(106): E2139 Declaration missing ;
[C++ Error] pcap-bpf.h(107): E2238 Multiple declaration for 'u_short'
[C++ Error] pcap-bpf.h(106): E2344 Earlier declaration of 'u_short'
[C++ Error] pcap-bpf.h(107): E2139 Declaration missing ;
[C++ Error] pcap-bpf.h(707): E2139 Declaration missing ;
[C++ Error] pcap-bpf.h(708): E2139 Declaration missing ;
[C++ Error] pcap-bpf.h(709): E2238 Multiple declaration for 'u_char'
[C++ Error] pcap-bpf.h(708): E2344 Earlier declaration of 'u_char'
[C++ Error] pcap-bpf.h(709): E2139 Declaration missing ;
[C++ Error] pcap.h(123): E2139 Declaration missing ;
[C++ Error] pcap.h(124): E2139 Declaration missing ;
[C++ Error] pcap.h(125): E2238 Multiple declaration for 'u_short'
[C++ Error] pcap.h(124): E2344 Earlier declaration of 'u_short'
[C++ Error] pcap.h(125): E2139 Declaration missing ;
[C++ Error] pcap.h(127): E2238 Multiple declaration for 'bpf_u_int32'
[C++ Error] pcap.h(123): E2344 Earlier declaration of 'bpf_u_int32'
[C++ Error] pcap.h(127): E2139 Declaration missing ;
[C++ Error] pcap.h(128): E2238 Multiple declaration for 'bpf_u_int32'
[C++ Error] pcap.h(123): E2344 Earlier declaration of 'bpf_u_int32'
[C++ Error] pcap.h(128): E2139 Declaration missing ;
[C++ Error] pcap.h(129): E2238 Multiple declaration for 'bpf_u_int32'
[C++ Error] pcap.h(123): E2344 Earlier declaration of 'bpf_u_int32'
[C++ Error] pcap.h(129): E2139 Declaration missing ;
[C++ Error] pcap.h(151): E2450 Undefined structure 'timeval'
[C++ Error] pcap.h(151): E2228 Too many error or warning messages

Подскажите, пожалуйста, в чем проблема?
PM MAIL WWW   Вверх
volvo877
Дата 30.9.2008, 17:54 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Комодератор
Сообщений: 2073
Регистрация: 15.11.2004

Репутация: 13
Всего: 116



В файле pcap.h есть строки типа
Код
#if defined(WIN32)

, но Билдер не определяет WIN32, вместо этого определяется __WIN32__... Попробуй добавить строку 
Код
#define WIN32
 перед подключением pcap.h, если ошибок станет меньше - значит, это и есть причина...
PM MAIL   Вверх
criz
Дата 30.9.2008, 18:21 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 63
Регистрация: 13.2.2008

Репутация: нет
Всего: нет



Добавил:
Код

#define WIN32
#define WPCAP
#define HAVE_REMOTE

Результат:
Код

[C++ Error] ws2tcpip.h(232): E2141 Declaration syntax error
[C++ Error] ws2tcpip.h(327): E2139 Declaration missing ;
[C++ Error] ws2tcpip.h(328): E2238 Multiple declaration for 'sockaddr_gen'
[C++ Error] ws2tcpip.h(327): E2344 Earlier declaration of 'sockaddr_gen'
[C++ Error] ws2tcpip.h(328): E2139 Declaration missing ;
[C++ Error] ws2tcpip.h(329): E2238 Multiple declaration for 'sockaddr_gen'
[C++ Error] ws2tcpip.h(327): E2344 Earlier declaration of 'sockaddr_gen'
[C++ Error] ws2tcpip.h(329): E2139 Declaration missing ;
[C++ Error] ws2tcpip.h(469): E2141 Declaration syntax error
[C++ Error] ws2tcpip.h(519): E2303 Type name expected
[C++ Error] wspiapi.h(39): E2303 Type name expected
[C++ Error] wspiapi.h(666): E2303 Type name expected
[C++ Error] wspiapi.h(866): E2141 Declaration syntax error
[C++ Error] wspiapi.h(867): E2451 Undefined symbol 'rgtGlobal'
[C++ Error] wspiapi.h(867): E2109 Not an allowed type
[C++ Warning] wspiapi.h(871): W8019 Code has no effect
[C++ Error] wspiapi.h(871): E2379 Statement missing ;
[C++ Error] wspiapi.h(872): E2140 Declaration is not allowed here
[C++ Error] wspiapi.h(873): E2140 Declaration is not allowed here
[C++ Error] wspiapi.h(933): E2451 Undefined symbol 'rgtLocal'
[C++ Error] wspiapi.h(981): E2303 Type name expected
[C++ Warning] wspiapi.h(83): W8058 Cannot create pre-compiled header: code in header

:(
PM MAIL WWW   Вверх
volvo877
Дата 30.9.2008, 20:19 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Комодератор
Сообщений: 2073
Регистрация: 15.11.2004

Репутация: 13
Всего: 116



Хм... Не знаю, приведенный тобой код у меня на BDS 2007 нормально откомпилировался вот в таком виде:
Код

#define WIN32
#define WPCAP
#define HAVE_U_INT8_T

#include "pcap.h"
#include "remote-ext.h"
... // дальше - то что было у тебя, буква в букву


(ничего не устанавливал, просто взял H-файлы, твой код и создал новый проект. Естественно, линкер это все у меня "зарежет", ибо библиотеки я тоже не добавлял. Однако компилируется успешно.)
PM MAIL   Вверх
criz
Дата 30.9.2008, 21:27 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 63
Регистрация: 13.2.2008

Репутация: нет
Всего: нет



Прошу прощения. Эти ошибки выдаются при выполнении команды `Make Project1'. Компиляция ошибки не выдает.
PM MAIL WWW   Вверх
criz
Дата 1.10.2008, 19:30 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 63
Регистрация: 13.2.2008

Репутация: нет
Всего: нет



Все, вроде сделано. Ошибок при сборке не наблюдается smile
Код

#include <winsock.h>
#include "inc/pcap.h"
#include "inc/remote-ext.h"

//---------------------------------------------------------------------------
#pragma comment(lib,"wpcap.lib")
#pragma comment(lib,"packet.lib")

Да, еще пришлось в хедерах заменить u_int/char/short на unsigned int/char/short.

Это сообщение отредактировал(а) criz - 1.10.2008, 20:43
PM MAIL WWW   Вверх
criz
Дата 3.10.2008, 21:57 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 63
Регистрация: 13.2.2008

Репутация: нет
Всего: нет



Не стал начинать новую тему, ибо проблема из той же области: Builder + wpcap smile
Решил я сделать вывод информации в Memo. 
Вот исходник (он почти такой же, как и в перовм сообщении):
Код

#include <vcl.h>
#pragma hdrstop

#include <winsock.h>
#include <time.h>
#define HAVE_REMOTE
#include "inc/pcap.h"
#include "inc/remote-ext.h"

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
#pragma comment(lib,"wpcap.lib")
#pragma comment(lib,"packet.lib")

TForm1 *Form1;
TMemo *Memo1;

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;

/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------


void __fastcall TForm1::Button1Click(TObject *Sender)
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
u_int netmask;
char packet_filter[] = "ip and udp";
struct bpf_program fcode;

    /* Retrieve the device list */
    if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
    {
                Memo1->Lines->Add("Error in pcap_findalldevs:" + IntToStr(errbuf));
        exit(1);
    }

    /* Print the list */

    inum = 2;

    /* Jump to the selected adapter */
    for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);

    /* Open the adapter */
    if ((adhandle= pcap_open(d->name, 65536, PCAP_OPENFLAG_PROMISCUOUS, 1000,  NULL, errbuf)) == NULL)
    {
                Memo1->Lines->Add("Unable to open the adapter.");
        pcap_freealldevs(alldevs);
        exit(1);
    }

    /* Check the link layer. We support only Ethernet for simplicity. */

    if(d->addresses != NULL)
        netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
    else
        netmask=0xffffff;
    //compile the filter
    if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0 )
    {
                Memo1->Lines->Add("Unable to compile the packet filter. Check the syntax.");
        pcap_freealldevs(alldevs);
        exit(-1);
    }

    if (pcap_setfilter(adhandle, &fcode)<0)
    {
                Memo1->Lines->Add("Error setting the filter.");
        pcap_freealldevs(alldevs);
        exit(-1);
    }
    pcap_freealldevs(alldevs);
    pcap_loop(adhandle, 0, packet_handler, NULL);
}

void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
        TForm *Form1;
    ip_header *ih;
    udp_header *uh;
    u_int ip_len;
    u_short sport,dport;

    ih = (ip_header *) (pkt_data + 14); //length of ethernet header

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

    /* convert from network byte order to host byte order */
    sport = ntohs( uh->sport );
    dport = ntohs( uh->dport );

    /* print ip addresses and udp ports */
    printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d\n",
        ih->saddr.byte1,
        ih->saddr.byte2,
        ih->saddr.byte3,
        ih->saddr.byte4,
        sport,
        ih->daddr.byte1,
        ih->daddr.byte2,
        ih->daddr.byte3,
        ih->daddr.byte4,
        dport);
        Memo1->Lines->Add(ih->saddr.byte1 + ih->saddr.byte2 + ih->saddr.byte3 + ih->saddr.byte4);
}

При нажатии на Button1 программа подвисает... в чем причина?
Если использовать трассировку(F7/F8), то билдер ругается на
Код

        Memo1->Lines->Add(ih->saddr.byte1 + ih->saddr.byte2 + ih->saddr.byte3 + ih->saddr.byte4);


P.S. Просьба к администраторам и модераторам: Нельзя ли переименовать данный топик в "Builder + wpcap" или что-нибудь подобное smile

Это сообщение отредактировал(а) criz - 4.10.2008, 06:57
PM MAIL WWW   Вверх
criz
Дата 4.10.2008, 19:15 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 63
Регистрация: 13.2.2008

Репутация: нет
Всего: нет



Товарищи, помогите плиз решить проблему. В понедельник сдавать надо...а я даже не знаю где копать :(
PM MAIL WWW   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "С++ Builder"
Rrader

Запрещается!

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми компонентами

  • Литературу по С++ Builder обсуждаем здесь
  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Настоятельно рекомендуем заглянуть в DRKB (Delphi Russian Knowledge Base) - крупнейший в рунете сборник материалов по Дельфи


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Rrader.

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C++ Builder | Следующая тема »


 




[ Время генерации скрипта: 0.1337 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.