Exemple #1
0
int main(int argc, char **argv) {
    char errbuf[PCAP_ERRBUF_SIZE];
    struct pcap_pkthdr *pkthdr;
    const u_char *pkt_data;

    Options options;

    parse_args(argc, argv, &options);

    if(options.list_devices) {
        show_devices();
        exit(0);
    }

    // Create Handles for in and out
    pcap_t *in_handle = pcap_create(argv[1], errbuf);
    pcap_t *out_handle = pcap_create(argv[1], errbuf);

    if(!in_handle | !out_handle )
        exit_error(errbuf, -1);
    
    int result = 0;

    // Set timeout
    result = pcap_set_timeout(in_handle, 1); // Header size up to window size
    result = pcap_set_timeout(out_handle, 1); // Header size up to window size
    handle_pcap_errors(in_handle, result, "set_timeout");
    handle_pcap_errors(out_handle, result, "set_timeout");



    // Activate!
    result = pcap_activate(out_handle);
    result = pcap_activate(in_handle);
    handle_pcap_errors(out_handle, result, "pcap_activate");
    handle_pcap_errors(in_handle, result, "pcap_activate");
    // Set Filter
    filter_on_port(out_handle, "src port ", options.port_str);
    filter_on_port(in_handle, "dst port ", options.port_str);


    // Count packet lenghts on port
    int out_byte_count = 0;
    int in_byte_count = 0;

    for(int i = 0; i < 100; i++) {
        pcap_next_ex(out_handle, &pkthdr, &pkt_data);
        out_byte_count += pkthdr->len;

        pcap_next_ex(in_handle, &pkthdr, &pkt_data);
        in_byte_count += pkthdr->len;
    }

    printf("In Bytes: %d\n", in_byte_count);
    printf("Out Bytes: %d\n", out_byte_count);

    return 0;
}
Hushort _recv_frame( Hubyte *frame )
{
    int res;
    const Hubyte *packet;
    struct pcap_pkthdr *hdr;
    struct ether_header *eptr;
    short len;
    
    res = pcap_next_ex( eth_cap, &hdr, &packet );
    while( res != 1 )   res = pcap_next_ex( eth_cap, &hdr, &packet );

    len = hdr->len;
    while( --len >= 0 ) frame[len] = packet[len];
    
    return hdr->len;
}
/* Copy the whole capture into the shared memory */
void copy_capture(struct shmstruct *ptr)
{
u_int32_t cap_len;
int r;
struct pcap_pkthdr *pkthdr;
const u_char *packet;
pkt_handle *hndl;
uint counter= 0;

	while ((r = pcap_next_ex (ConfigParams.in_descr, &pkthdr, &packet)) == 1)
	{
		if (counter >= QUEUE_SIZE)
		{
			error("Too many packet for queue");
			exit(-2);
		}
		
		hndl = &ptr->queues[counter];
		cap_len = pkthdr->caplen;
		hndl->cap_len = cap_len;

		memcpy(hndl->pkt_data, packet, cap_len);

		counter++;
	}
	/* insert a fake trailing packet to signal workers that capture is over */
	log("Inserting last packet into queue");
		
	hndl = &ptr->queues[counter];
	hndl->cap_len = 0;
}
Exemple #4
0
int
Ethernet_receivePacket(EthernetSocket self, uint8_t* buffer, int bufferSize)
{
	struct pcap_pkthdr* header;
	uint8_t* packetData;

	int pcapCode = pcap_next_ex(self->rawSocket, &header, (const unsigned char**) &packetData);

	if (pcapCode > 0) {
		int packetSize = header->caplen;

		if (packetSize > bufferSize)
			packetSize = bufferSize;

		memcpy(buffer, packetData, packetSize);

		return packetSize;
	}
	else {
		if (pcapCode < 0)
			printf("winpcap error\n");

		return 0;
	}
}
Exemple #5
0
client_event * client_event_read(pcap_t * handle) {
  while (1) {
    struct pcap_pkthdr * header;
    const u_char * buffer;
    int ret = pcap_next_ex(handle, &header, &buffer);
    if (ret < 0) {
      return NULL;
    }
    if (ret != 1 || header->caplen < 4) {
      continue;
    }

    size_t radiotapLen = (size_t)((uint16_t *)buffer)[1];
    if (header->caplen < radiotapLen) {
      continue;
    }

    const u_char * macPacket = buffer + radiotapLen;
    size_t macPacketLen = (size_t)header->caplen - radiotapLen;
    if (!is_data_packet(macPacket, macPacketLen)) {
      continue;
    }

    client_event * res = read_mac_info(macPacket, macPacketLen);
    res->data_size = macPacketLen;
    res->timestamp = header->ts;
    res->rssi = radiotap_rssi(buffer);
    res->request_info = http_req_in_packet(macPacket, macPacketLen);
    res->response_info = http_resp_in_packet(macPacket, macPacketLen);
    return res;
  }
}
Exemple #6
0
    void
epcap_loop(EPCAP_STATE *ep)
{
    pcap_t *p = ep->p;
    struct pcap_pkthdr *hdr = NULL;
    const u_char *pkt = NULL;

    int read_packet = 1;
    int datalink = pcap_datalink(p);

    while (read_packet) {
        switch (pcap_next_ex(p, &hdr, &pkt)) {
            case 0:     /* timeout */
                VERBOSE(1, "timeout reading packet");
                break;
            case 1:     /* got packet */
                epcap_response(hdr, pkt, datalink);
                break;
            case -2:    /* eof */
                VERBOSE(1, "end of file");
                epcap_ctrl("eof");
                read_packet = 0;
                break;
            case -1:    /* error reading packet */
                VERBOSE(1, "error reading packet");
                /* fall through */
            default:
                read_packet = 0;
        }
    }
}
Exemple #7
0
/*
 * 过滤得到登录成功包
 * @return: 0: 成功获取
 *          -1: 超时
 *          -2: 服务器中止登录,密码错误吧
 */
static int filte_success(pcap_t *skfd)
{
    int stime = time((time_t*)NULL);
    struct pcap_pkthdr *pkt_hd;
    const uchar *recvbuff;
    int timeout;
    for (; time((time_t*)NULL)-stime <= TIMEOUT;) {
        timeout = pcap_next_ex(skfd, &pkt_hd, &recvbuff);
        if (0 >= timeout) return -1;
        FORMAT_RECVPKT(recvbuff);
        if (recvethii->type == htons(ETHII_8021X)
                && mac_equal(recvethii->dst_mac, client_mac)
                && recveapol->type == EAPOL_PACKET ) {
            if (recveap->id == sendeap->id
                    && recveap->code == EAP_CODE_SUCS) {
                _D("id: %d login success.\n", sendeap->id);
                return 0;
            } else if (recveap->id == sendeap->id
                    && recveap->code == EAP_CODE_FAIL) {
                _D("id: %d fail.\n", sendeap->id);
                return -2;
            }
        }
    }
    return -1;
}
Exemple #8
0
int read_rtp_nb(const char *fpcap, int dport)
{
    pcap_t *fp;
    char errbuf[PCAP_ERRBUF_SIZE];

    struct pcap_pkthdr *header;
    const u_char *pkt_data;
    int res, pkt_count = 0;


    ip_header *ih;
    udp_header *uh;
    u_int ip_len;

    fp = pcap_open_offline(fpcap, errbuf);

    /* Retrieve the packets from the file */
    while((res = pcap_next_ex(fp, &header, &pkt_data)) >= 0) {

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

        if( ntohs(uh->dport) ==	dport) {
            pkt_count++;
        }

    }

    pcap_close(fp);
    return pkt_count;
}
Exemple #9
0
ssize_t us_rawnet_recv(
    us_rawnet_context_t *self, uint8_t src_mac[6], uint8_t dest_mac[6], void *payload_buf, ssize_t payload_buf_max_size )
{
    ssize_t r = -1;
    pcap_t *m_pcap = (pcap_t *)self->m_pcap;

    if ( m_pcap )
    {
        const uint8_t *data;
        struct pcap_pkthdr *header;
        int e = pcap_next_ex( m_pcap, &header, &data );

        if ( e == 1 && ( (ssize_t)header->caplen - 14 ) <= payload_buf_max_size )
        {
            r = header->caplen - 14;
            memcpy( payload_buf, &data[14], r );
            if ( src_mac )
            {
                memcpy( src_mac, &data[6], 6 );
            }
            if ( dest_mac )
            {
                memcpy( dest_mac, &data[0], 6 );
            }
        }
    }
    return r;
}
Exemple #10
0
void my_sniffer::run(){
    //qDebug("[[[");
    qDebug("start a thread to get data");
    int packet_id=0;
    while(!stopped)
    {
        int temp;
     //   pkthdr=new struct pcap_pkthdr();
       // packet=new const u_char();

        temp=pcap_next_ex(dev_haddle,&pkthdr,&packet);
        if(temp!=1)
        {
          ;//  qDebug("error in the pcap_next_ex  and  the temp is %d",temp);
        }
        else if(temp==1)
        {
            packet_id++;
            qDebug("in the run");
           // const u_char *packet=mydata[row];// get the packet been selected
            //struct pcap_pkthdr *pkthdr=mypkthdr[row];
            emit send_capture_pcaket(pkthdr,packet,packet_id);
//            emit send_capture_packettomydeal(pkthdr,packet);
        }
      //  stopped=false;
    }
    qDebug("sniffer thread is running");
    if(dev_haddle)
     {
        qDebug("close dev_handle");
        pcap_close(dev_haddle);
     }

}
void ReceivePacketThread::recvTCPSYNACKPortScanPacket()
{
    pcap_t *adhandle = this->handle;
    int res;
    struct pcap_pkthdr * pktHeader;
    const u_char * pktData;
    while (!scanIsFinished) {
        if ((res = pcap_next_ex(adhandle, &pktHeader, &pktData)) >= 0) {
            etherpacket->setData(pktData);
            if ((etherpacket->getEtherNetType() == my_htons(IP_TYPE))){
                ipheaderpacket->setData(pktData);
                if((ipheaderpacket->getProtocolType() == "TCP")){
                    tcppacket->setData(pktData);
                    if((ipheaderpacket->getDestIpAddStr() == QString(hostInfo->ip)) &&
                        (ipheaderpacket->getSourceIpAddStr() == scanIp)){
                        // 端口开放
                        if(tcppacket->getFlag() == (TCP_SYN_ACK)){
                            //qDebug() << my_htons(tcppacket->getSrcPort()) << " 端口已开放";

                            QString service = portServiceMap->getService(my_htons(tcppacket->getSrcPort()));
                            QString msg = QString("端口:%1  协议:tcp  服务:%2").arg(QString::number(my_htons(tcppacket->getSrcPort())),service);
                            //qDebug()<< msg;
                            emit portScanRecvUpdataSig(msg);
                        }
                        // 端口未开放
                        else if(tcppacket->getFlag() == (TCP_RST_ACK)){
                            //qDebug() << my_htons(tcppacket->getSrcPort()) << " 端口未开放";
                        }
                    }
                }
            }
        }
    }
}
void ReceivePacketThread::recvArpScanPacket()
{
    pcap_t *adhandle = this->handle;
    int res;    
    struct pcap_pkthdr * pktHeader;
    const u_char * pktData;
    while (!scanIsFinished) {
        if ((res = pcap_next_ex(adhandle, &pktHeader, &pktData)) >= 0) {            
            arppacket->setData(pktData);
            if ((arppacket->getEtherNetType()) == my_ntohs(ARP_TYPE)
                    && ((arppacket->getOperationField()) == my_ntohs(ARP_REPLY))
                ){
                    QPair<QString,QString> pair;
                    pair.first = QString(my_iptos(arppacket->getSourceIpAdd()));
                    pair.second = arppacket->getSourceMacAdd();

                    emit scanGetHostInfoSig(pair);
//                qDebug("-------------------------------------------\n");
//                qDebug("IP Address: %s",my_iptos(arppacket->getSourceIpAdd()));
//                qDebug() << arppacket->getSourceMacAdd();
//                qDebug("\n");
            }
        }        
    }
}
Exemple #13
0
int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
{
    struct pcap_pkthdr *header  = NULL;
    const u_char *pktdata = NULL;
    int ret = 0;

    if (initFinished == 0)
    {
        return DPDKPCAP_FAILURE;
    }

    for (;;)
    {
        ret = pcap_next_ex(p, &header, &pktdata);
        if (ret == 1)
        {
            callback(user, header, pktdata);
        }

        if (!PACKET_COUNT_IS_UNLIMITED(cnt))
        {
            cnt -= ret;
            if (cnt <= 0)
                return DPDKPCAP_OK;
        }
    }

    return DPDKPCAP_FAILURE;
}
Exemple #14
0
UINT CNILayer::ReadingThread(LPVOID pParam)
{
	struct pcap_pkthdr *header;
	const u_char *pkt_data;
	int result;

	CNILayer *pNI = (CNILayer *)pParam;
	
	while(pNI->m_thrdSwitch) // 패킷 체크
	{
		// 패킷 읽어오기
		result = pcap_next_ex(pNI->m_AdapterObject,&header,&pkt_data);
		
		if(result==0){
		//	AfxMessageBox("패킷 없음");
		}
		else if(result==1){
		//	AfxMessageBox("패킷 있음");
			pNI->Receive((u_char *)pkt_data);
		}
		else if(result<0){
		//	AfxMessageBox("패킷 오류");
		}
	}

	return 0;
}
static void rs_got_packet(UNUSED fr_event_list_t *el, int fd, void *ctx)
{
	static uint64_t	count = 0;	/* Packets seen */
	rs_event_t	*event = ctx;
	pcap_t		*handle = event->in->handle;

	int i;
	int ret;
	const uint8_t *data;
	struct pcap_pkthdr *header;

	for (i = 0; (event->in->type == PCAP_FILE_IN) || (i < RS_FORCE_YIELD); i++) {
		ret = pcap_next_ex(handle, &header, &data);
		if (ret == 0) {
			/* No more packets available at this time */
			return;
		}
		if (ret == -2 && (event->in->type == PCAP_FILE_IN)) {
			INFO("Done reading packets (%s)", event->in->name);
			fr_event_fd_delete(events, 0, fd);
			return;
		}
		if (ret < 0) {
			ERROR("Error requesting next packet, got (%i): %s", ret, pcap_geterr(handle));
			return;
		}

		count++;
		rs_packet_process(count, event, header, data);
	}
}
Exemple #16
0
/**
 * Forward data to hijacker
 *
 */
static ssize_t forward_to_hijacker ( int fd, struct hijack *hijack ) {
    struct pcap_pkthdr *pkt_header;
    const unsigned char *pkt_data;
    ssize_t len;

    /* Receive packet from network */
    if ( pcap_next_ex ( hijack->pcap, &pkt_header, &pkt_data ) < 0 ) {
        logmsg ( LOG_ERR, "read from hijacked port failed: %s\n",
                 pcap_geterr ( hijack->pcap ) );
        return -1;
    }
    if ( pkt_header->caplen != pkt_header->len ) {
        logmsg ( LOG_ERR, "read partial packet (%d of %d bytes)\n",
                 pkt_header->caplen, pkt_header->len );
        return -1;
    }
    if ( pkt_header->caplen == 0 )
        return 0;
    len = pkt_header->caplen;

    /* Write packet to hijacker */
    if ( write ( fd, pkt_data, len ) != len ) {
        logmsg ( LOG_ERR, "write to hijacker failed: %s\n",
                 strerror ( errno ) );
        return -1;
    }

    hijack->rx_count++;
    return len;
};
Exemple #17
0
UINT Cappacketlivethread(LPVOID pParam)//抓包线程函数
{
	//CMainFrame *p_frame=(CMainFrame*)AfxGetMainWnd();
	//int m_exsn=p_frame->m_myprosheet.m_page2.m_thread_num;
	//int m_stoptime=p_frame->m_myprosheet.m_page2.m_stoptime;
	//int m_thread_index=0;
	for(int i=0;i<m_mystruct.m_packetlimit;i++)//线程数目
	{	
		if (::WaitForSingleObject(m_stoptimeup,0)==WAIT_OBJECT_0)
		{
			//m_thread_index=i;
			m_mystruct.m_count=i;
			break;
		} 
        pcap_next_ex(m_mystruct.pcap_handle,&m_mystruct.protocol_header,&m_mystruct.pkt_data);//句柄,协议头,数据包
		if ((m_mystruct.protocol_header->len)>m_mystruct.m_pl)//判断是否在规定长度以内
		{	
			i--;
			continue;
		}  
		pcap_dump((u_char*)m_mystruct.dumpfile,m_mystruct.protocol_header,m_mystruct.pkt_data);
		m_mystruct.m_count=i;
	} 
	m_eventEnd.SetEvent();
	return 0;
}
Exemple #18
0
static int lpcap_next(lua_State* L)
{
    pcap_t* cap = checkpcap(L);
    struct pcap_pkthdr* pkt_header = NULL;
    const u_char* pkt_data = NULL;
    int e = pcap_next_ex(cap, &pkt_header, &pkt_data);

    /* Note: return values don't have names, they are documented numerically
       in the man page. */
    switch(e) {
        case 1: /* success */
            return pushpkt(L, pkt_header, pkt_data);
        case 0: /* read live, and timeout occurred */
            lua_pushnil(L);
            lua_pushstring(L, "timeout");
            return 2;
        case -2: /* read from a savefile, and no more packets */
            lua_pushnil(L);
            lua_pushstring(L, "closed");
            return 2;
        case -1: /* an error occurred */
            return pusherr(L, cap);
    }
    return luaL_error(L, "unreachable");
}
u_int32_t nbNetVmPortLocalAdapter::SrcPollingFunctionWinPcap(void * ptr, nvmExchangeBufferState *buffer, int *dummy)
{
	struct pcap_pkthdr *header;
	u_char *pkt_data;
	int res;

	nbNetVmPortLocalAdapter *ClassHandler = (nbNetVmPortLocalAdapter *) ptr;
	
	NETVM_ASSERT(ClassHandler->m_WinPcapDevice != NULL, __FUNCTION__ "  - WinPcapDevice not opened, this is weird");

	do
	{
		res = pcap_next_ex( (pcap_t*)ClassHandler->m_WinPcapDevice, &header, (const u_char**)&pkt_data);

		NETVM_ASSERT(res >= 0, __FUNCTION__ "  - I don't know what to do, the next_ex failed... GV");
	    
		if (res == 1)
		{
			buffer->timestamp_sec = header->ts.tv_sec;
			buffer->timestamp_usec = header->ts.tv_usec;
			buffer->pkt_pointer=pkt_data;
			buffer->pktlen=header->len;
			buffer->infolen=0;
			return nbSUCCESS;
		}
	}
	while (res == 0);
	return nbFAILURE;
}
Exemple #20
0
/*******************************************************************************
 * The pcap2Daemon function is spawned as a thread.
 * It takes packets from winPCap and relays them to the coLinux Daemon.
 */
DWORD WINAPI
pcap2Daemon(LPVOID lpParam)
{
	int pcap_status;
	co_rc_t rc;

	while (1) {
		// Attempt to receive packet from WPcap.
		pcap_status = pcap_next_ex(pcap_packet.adhandle,
					   &pcap_packet.pkt_header,
					   &pcap_packet.buffer);
		switch (pcap_status) {
		case 1:	/* Packet read */
			rc = co_win32_pcap_read_received(&pcap_packet);
			if (!CO_OK(rc))
				return 0;
			break;

		case 0:	/* Timeout  */
			break;

		default:
			/* Error or EOF(offline capture only) */
			co_debug("Unexpected error reading from winPCap.\n");
			ExitProcess(0);
			return 0;
			break;
		}
	}

	// We should never get to here.
	co_debug("Unexpected exit of winPCap read loop.\n");
	ExitProcess(0);
	return 0;
}
Exemple #21
0
U8 *pcapRawsockGetRxFrame(void *pvRawsock, U32 timeout, unsigned int *offset, unsigned int *len)
{
	pcap_rawsock_t *rawsock = (pcap_rawsock_t*)pvRawsock;

	rawsock->rxHeader = 0;
	const u_char *packet = 0;
	int ret;

	if (rawsock) {
		ret = pcap_next_ex(rawsock->handle, &rawsock->rxHeader, &packet);
		switch(ret) {
		case 1:
			*offset = 0;
			*len = rawsock->rxHeader->caplen;
			return (U8*)packet;
		case -1:
			AVB_LOGF_ERROR("pcap_next_ex failed: %s", pcap_geterr(rawsock->handle));
			break;
		case 0:
			// timeout;
			break;
		case -2:
			// no packets to be read from savefile
			// this should not happened
			break;
		default:
			break;
		}
	}

	return NULL;
}
Exemple #22
0
/*Reads the next packet from pcap_next() and validates the FCS. */
unsigned char *next_packet(struct pcap_pkthdr *header)
{
	const unsigned char *packet = NULL;
	struct pcap_pkthdr *pkt_header;
	static int warning_shown = 0;
	int status;

	/* Loop until we get a valid packet, or until we run out of packets */
	while((status = pcap_next_ex(get_handle(), &pkt_header, &packet)) == 1 || !status)
	{
		if(!status) continue; /* timeout */

		memcpy(header, pkt_header, sizeof(*header));

		if(get_validate_fcs() && !check_fcs(packet, header->len)) {
			if(!warning_shown)
				cprintf(INFO, "[!] Found packet with bad FCS, skipping...\n");
			warning_shown = 1;
			continue;
		}

		break;
	}

	return (void*)packet;
}
Exemple #23
0
static void *uaenet_trap_threadr (void *arg)
{
	struct uaenetdatawin32 *sd = (struct uaenetdatawin32*)arg;
	struct pcap_pkthdr *header;
	const u_char *pkt_data;

	uae_set_thread_priority (NULL, 1);
	sd->threadactiver = 1;
	uae_sem_post (&sd->sync_semr);
	while (sd->threadactiver == 1) {
		int r;
		r = pcap_next_ex (sd->fp, &header, &pkt_data);
		if (r == 1) {
			uae_sem_wait (&sd->change_sem);
			sd->gotfunc ((struct s2devstruct*)sd->user, pkt_data, header->len);
			uae_sem_post (&sd->change_sem);
		}
		if (r < 0) {
			write_log (L"pcap_next_ex failed, err=%d\n", r);
			break;
		}
	}
	sd->threadactiver = 0;
	uae_sem_post (&sd->sync_semr);
	return 0;
}
static void prvInterruptSimulator( void *pvParameters )
{
static struct pcap_pkthdr *pxHeader;
const unsigned char *pucPacketData;
extern QueueHandle_t xEMACEventQueue;
long lResult;

	/* Just to kill the compiler warning. */
	( void ) pvParameters;

	for( ;; )
	{
		/* Get the next packet. */
		lResult = pcap_next_ex( pxOpenedInterfaceHandle, &pxHeader, &pucPacketData );
		if( lResult == 1 )
		{
			if( pxlwIPNetIf != NULL )
			{
				prvEthernetInput( pucPacketData, pxHeader->len );
			}
		}
		else
		{
			/* There is no real way of simulating an interrupt.  
			Make sure other tasks can run. */
			vTaskDelay( 5 );
		}
	}
}
Exemple #25
0
nmsg_res
nmsg_pcap_input_read_raw(nmsg_pcap_t pcap, struct pcap_pkthdr **pkt_hdr,
			 const uint8_t **pkt_data, struct timespec *ts)
{
	int pcap_res;

	assert(pcap->raw == true);

	/* get the next frame from the libpcap source */
	pcap_res = pcap_next_ex(pcap->handle, pkt_hdr, (const u_char **) pkt_data);
	if (pcap_res == 0)
		return (nmsg_res_again);
	if (pcap_res == -1) {
		_nmsg_dprintf(1, "%s: pcap_next_ex() failed: %s\n", __func__,
			      pcap_geterr(pcap->handle));
		return (nmsg_res_pcap_error);
	}
	if (pcap_res == -2)
		return (nmsg_res_eof);

	/* get the time of packet reception */
	ts->tv_sec = (*pkt_hdr)->ts.tv_sec;
	ts->tv_nsec = (*pkt_hdr)->ts.tv_usec * 1000;

	return (nmsg_res_success);
}
Exemple #26
0
nmsg_res
nmsg_pcap_input_read(nmsg_pcap_t pcap, struct nmsg_ipdg *dg,
		     struct timespec *ts)
{
	const u_char *pkt_data;
	int pcap_res;
	struct pcap_pkthdr *pkt_hdr;

	assert(pcap->raw == false);

	/* get the next frame from the libpcap source */
	pcap_res = pcap_next_ex(pcap->handle, &pkt_hdr, &pkt_data);
	if (pcap_res == 0)
		return (nmsg_res_again);
	if (pcap_res == -1) {
		_nmsg_dprintf(1, "%s: pcap_next_ex() failed: %s\n", __func__,
			      pcap_geterr(pcap->handle));
		return (nmsg_res_pcap_error);
	}
	if (pcap_res == -2)
		return (nmsg_res_eof);

	/* get the time of packet reception */
	ts->tv_sec = pkt_hdr->ts.tv_sec;
	ts->tv_nsec = pkt_hdr->ts.tv_usec * 1000;

	/* parse the frame */
	return (nmsg_ipdg_parse_pcap(dg, pcap, pkt_hdr, pkt_data));
}
Exemple #27
0
int
process_stream(const char *input, const char *output, ifnet_t *ifp)
{
	pcap_t *pcap;
	char pcap_errbuf[PCAP_ERRBUF_SIZE];
	struct pcap_pkthdr *phdr;
	const uint8_t *data;
	FILE *fp;

	pcap = pcap_open_offline(input, pcap_errbuf);
	if (pcap == NULL) {
		errx(EXIT_FAILURE, "pcap_open_offline failed: %s", pcap_errbuf);
	}
	fp = output ? fopen(output, "w") : stdout;
	if (fp == NULL) {
		err(EXIT_FAILURE, "fopen");
	}
	fprintf(fp, "#FL %5s %3s %11s %11s %11s %11s %11s %11s %11s "
	    "%11s %11s %11s %5s %11s %11s %11s %5s\n",
	    "No", "Err", "Seq", "Ack", "TCP Len", "Win",
	    "Stream", "RetVal", "State",
	    "F.END", "F.MAXEND", "F.MAXWIN", "F.WSC",
	    "T.END", "T.MAXEND", "T.MAXWIN", "T.WSC");
	while (pcap_next_ex(pcap, &phdr, &data) > 0) {
		if (phdr->len != phdr->caplen) {
			warnx("process_stream: truncated packet");
		}
		process_tcpip(data, phdr->caplen, fp, ifp);
	}
	pcap_close(pcap);
	fclose(fp);

	return 0;
}
Exemple #28
0
UINT CNILayer::ReadingThread(LPVOID pParam)
{
	//////////////////////// fill the blank ///////////////////////////////
	struct pcap_pkthdr* header;
	const u_char* pkt_data;
	int result; 

	AfxBeginThread(FileTransferThread, (LPVOID)pParam);
	CNILayer* pNI = (CNILayer*) pParam;

	while(pNI->m_thrdSwitch)
	{
		result = pcap_next_ex(pNI->m_AdapterObject,&header,&pkt_data);

		if(result == 0)
		{
		}
		else if(result == 1)
		{
			pNI->Receive((u_char*)pkt_data);
		}
		else if(result < 0)
		{}
	}
	return 0;
	///////////////////////////////////////////////////////////////////////
}
Exemple #29
0
/* returns the number of octets in the PDU, or zero on failure */
uint16_t ethernet_receive(
    BACNET_ADDRESS * src,       /* source address */
    uint8_t * pdu,      /* PDU data */
    uint16_t max_pdu,   /* amount of space available in the PDU  */
    unsigned timeout    /* number of milliseconds to wait for a packet. we ommit it due to winpcap API. */
    )
{
    struct pcap_pkthdr *header;
    int res;
    u_char *pkt_data;
    uint16_t pdu_len = 0;       /* return value */

    /* Make sure the socket is open */
    if (!ethernet_valid()) {
        LogError("ethernet.c: invalid 802.2 ethernet interface descriptor!\n");
        return 0;
    }

    /* Capture a packet */
    res = pcap_next_ex(pcap_eth802_fp, &header, &pkt_data);
    if (res < 0) {
        char msgBuf[200];
        sprintf(msgBuf, "ethernet.c: error in receiving packet: %s\n",
            pcap_geterr(pcap_eth802_fp));
        return 0;
    } else if (res == 0)
        return 0;

    if (header->len == 0 || header->caplen == 0)
        return 0;

    /* the signature of an 802.2 BACnet packet */
    if ((pkt_data[14] != 0x82) && (pkt_data[15] != 0x82)) {
        /*eth_log_error("ethernet.c: Non-BACnet packet\n"); */
        return 0;
    }
    /* copy the source address */
    src->mac_len = 6;
    memmove(src->mac, &pkt_data[6], 6);

    /* check destination address for when */
    /* the Ethernet card is in promiscious mode */
    if ((memcmp(&pkt_data[0], Ethernet_MAC_Address, 6) != 0)
        && (memcmp(&pkt_data[0], Ethernet_Broadcast, 6) != 0)) {
        /*eth_log_error( "ethernet.c: This packet isn't for us\n"); */
        return 0;
    }

    (void) decode_unsigned16(&pkt_data[12], &pdu_len);
    pdu_len -= 3 /* DSAP, SSAP, LLC Control */ ;
    /* copy the buffer into the PDU */
    if (pdu_len < max_pdu)
        memmove(&pdu[0], &pkt_data[17], pdu_len);
    /* ignore packets that are too large */
    else
        pdu_len = 0;

    return pdu_len;
}
Exemple #30
0
/* Populates global *packet, returns status */
int getpacket(struct capture_data *capdata)
{

	/* Assume it's a libpcap file for now */
	int ret;
	ret = pcap_next_ex(p, &h, (const u_char **)&packet);
	return (ret);
}