当前位置: 首页>>代码示例>>C++>>正文


C++ pcap_close函数代码示例

本文整理汇总了C++中pcap_close函数的典型用法代码示例。如果您正苦于以下问题:C++ pcap_close函数的具体用法?C++ pcap_close怎么用?C++ pcap_close使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了pcap_close函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: get_interface_list


//.........这里部分代码省略.........
		/*
		 * Get the interface flags.
		 */
		memset(&ifrflags, 0, sizeof ifrflags);
		g_strlcpy(ifrflags.ifr_name, ifr->ifr_name,
		    sizeof ifrflags.ifr_name);
		if (ioctl(sock, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
			if (errno == ENXIO)
				goto next;
			if (err_str != NULL) {
				*err_str = g_strdup_printf(
				    "Can't get list of interfaces: SIOCGIFFLAGS error getting flags for interface %s: %s",
				    ifr->ifr_name, g_strerror(errno));
			}
			goto fail;
		}

		/*
		 * Skip interfaces that aren't up.
		 */
		if (!(ifrflags.ifr_flags & IFF_UP))
			goto next;

		/*
		 * Skip interfaces that we can't open with "libpcap".
		 * Open with the minimum packet size - it appears that the
		 * IRIX SIOCSNOOPLEN "ioctl" may fail if the capture length
		 * supplied is too large, rather than just truncating it.
		 */
		pch = pcap_open_live(ifr->ifr_name, MIN_PACKET_SIZE, 0, 0,
		    errbuf);
		if (pch == NULL)
			goto next;
		pcap_close(pch);

		/*
		 * If it's a loopback interface, add it at the end of the
		 * list, otherwise add it after the last non-loopback
		 * interface, so all loopback interfaces go at the end - we
		 * don't want a loopback interface to be the default capture
		 * device unless there are no non-loopback devices.
		 */
		loopback = ((ifrflags.ifr_flags & IFF_LOOPBACK) ||
		    strncmp(ifr->ifr_name, "lo", 2) == 0);
		if_info = if_info_new(ifr->ifr_name, NULL, loopback);
		if_info_add_address(if_info, &ifr->ifr_addr);
		if (loopback)
			il = g_list_append(il, if_info);
		else {
			il = g_list_insert(il, if_info, nonloopback_pos);
			/*
			 * Insert the next non-loopback interface after this
			 * one.
			 */
			nonloopback_pos++;
		}

	next:
#ifdef HAVE_SA_LEN
		ifr = (struct ifreq *) ((char *) ifr +
		    (ifr->ifr_addr.sa_len > sizeof(ifr->ifr_addr) ?
			ifr->ifr_addr.sa_len : sizeof(ifr->ifr_addr)) +
		    IFNAMSIZ);
#else
		ifr = (struct ifreq *) ((char *) ifr + sizeof(struct ifreq));
#endif
开发者ID:AndresVelasco,项目名称:wireshark,代码行数:67,代码来源:capture-pcap-util-unix.c

示例2: memset

void *recv_continuo_burst (void *param) {
	data_test *data = (data_test *)param;
	received_probe *recv_probe = &(data->probe[0]);
	settings *conf_settings = data->conf_settings;
	resume *result = data->result;
	int sockfd = -1, resize_buffer = DEFAULT_SOC_BUFFER, yes = 1;
	struct sockaddr receiver_addr;
	struct sockaddr_in *receiver_addr_in = (struct sockaddr_in *)&receiver_addr;

	/* pcap */
	char errbuf[PCAP_ERRBUF_SIZE];
	char expr[BUFFER_SIZE];
	char dev[BUFFER_SIZE];
	pcap_t* descr;
	struct bpf_program fp;        /* hold compiled program */
	bpf_u_int32 maskp;            /* subnet mask */
	bpf_u_int32 netp;             /* ip */

	memset (expr, 0, BUFFER_SIZE);
	memset (dev, 0, BUFFER_SIZE);
	snprintf (dev, BUFFER_SIZE, "%s", DEFAULT_INTERFACE_NAME);

	if (strlen(conf_settings->iface)) {
		if (pcap_lookupnet(conf_settings->iface, &netp, &maskp, errbuf)) {
			DEBUG_MSG (DEBUG_LEVEL_LOW, "Get Device %s error: %s\n", conf_settings->iface, errbuf);
			return NULL;
		}
		else {
			memset (dev, 0, BUFFER_SIZE);
			snprintf (dev, BUFFER_SIZE, "%s", conf_settings->iface);
		}
	}

	resize_buffer = conf_settings->recvsock_buffer * 1024;
	if (resize_socket_buffer (resize_buffer)) {
		DEBUG_MSG (DEBUG_LEVEL_LOW, "Could not resize socket buffers!!\n");
		return NULL;
	}

	sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	bzero(&receiver_addr, sizeof(receiver_addr));
	receiver_addr_in->sin_family = AF_INET;
	receiver_addr_in->sin_addr.s_addr = 0;
	receiver_addr_in->sin_port = htons(conf_settings->udp_port);

	if (setsockopt (sockfd, SOL_SOCKET, SO_RCVBUF, (const void *)&resize_buffer, sizeof(resize_buffer)) != 0) {
		DEBUG_MSG (DEBUG_LEVEL_LOW, "Could not resize receive socket buffers!!\n");
		return NULL;
	}

	if (setsockopt (sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
		DEBUG_LEVEL_MSG (DEBUG_LEVEL_LOW, "Could not set socket\n");
		return NULL;
	}

	if (bind(sockfd, (const struct sockaddr *)&receiver_addr, sizeof(receiver_addr))==-1) {
		DEBUG_LEVEL_MSG (DEBUG_LEVEL_LOW, "Could not bind!!\n");
		return NULL;
	}

	/* libpcap filter! */
	snprintf (expr, BUFFER_SIZE, "udp port %d", conf_settings->udp_port);

	/* open device for reading in promiscuous mode */
	descr = pcap_open_live (dev, BUFSIZ, 1, 0, errbuf); 
	if(descr == NULL) {
		DEBUG_MSG(DEBUG_LEVEL_LOW, "pcap_open_live(): %s\n", errbuf);
		return NULL;
	}
	data->handle = (void *)descr;
 
	/* Now we'll compile the filter expression*/
	if (pcap_compile (descr, &fp, expr, 0, netp) == -1) {
		DEBUG_MSG(DEBUG_LEVEL_LOW, "Error calling pcap_compile\n");
		return NULL;
	} 

	/* set the filter */
	if (pcap_setfilter (descr, &fp) == -1) {
		DEBUG_MSG(DEBUG_LEVEL_LOW, "Error setting filter\n");
		return NULL;
	}
	
	/* loop for callback function */
	pcap_loop (descr, -1, process_packet, (u_char *)data);

	close(sockfd);
	pcap_close (descr);

	result->loss_med = conf_settings->test.cont.pkt_num - recv_probe->received_packets;

	return NULL;
}
开发者ID:ascjunior,项目名称:UdpTester,代码行数:93,代码来源:continuo_burst.c

示例3: main

int main(int argc, char **argv)
{
	pcap_if_t *alldevs;
	pcap_if_t *d;
	int inum;
	int i=0;
	pcap_t *adhandle;
	char errbuf[PCAP_ERRBUF_SIZE];
	pcap_dumper_t *dumpfile;
	

    /* Check command line */
	if(argc != 2)
	{
        printf("usage: %s filename", argv[0]);
        return -1;
    }
    
	/* Retrieve the device list on the local machine */
	if (pcap_findalldevs(&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_live(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.
							 1,				// promiscuous mode (nonzero means promiscuous)
							 1000,			// read timeout
							 errbuf			// error buffer
							 )) == NULL)
	{
		fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return -1;
	}

	/* Open the dump file */
	dumpfile = pcap_dump_open(adhandle, argv[1]);

	if(dumpfile==NULL)
	{
		fprintf(stderr,"\nError opening output file\n");
		return -1;
	}
    
    printf("\nlistening on %s... Press Ctrl+C to stop...\n", d->description);
	
    /* At this point, we no longer need the device list. Free it */
    pcap_freealldevs(alldevs);
    
    /* start the capture */
    pcap_loop(adhandle, 0, packet_handler, (unsigned char *)dumpfile);

    pcap_close(adhandle);
    return 0;
}
开发者ID:52M,项目名称:npcap,代码行数:91,代码来源:savedump.c

示例4: message


//.........这里部分代码省略.........

	// save the socket ID for the next calls
	fp->rmt_sockctrl= sockctrl;	// Needed to send an error on the ctrl connection

	// Now I can set the filter
	if ( daemon_unpackapplyfilter(fp, &nread, &plen, errbuf) )
		goto error;


	// Now, I can send a RPCAP start capture reply message
	if ( sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
		RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE) == -1)
		goto error;

	rpcap_createhdr( (struct rpcap_header *) sendbuf, RPCAP_MSG_STARTCAP_REPLY, 0, sizeof(struct rpcap_startcapreply) );

	startcapreply= (struct rpcap_startcapreply *) &sendbuf[sendbufidx];
	
	if ( sock_bufferize(NULL, sizeof(struct rpcap_startcapreply), NULL,
		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE) == -1)
		goto error;

	memset(startcapreply, 0, sizeof(struct rpcap_startcapreply) );
	startcapreply->bufsize= htonl(fp->bufsize);

	if (!serveropen_dp)
	{
		unsigned short port = (unsigned short)strtoul(portdata,NULL,10);
		startcapreply->portdata= htons(port);
	}

	if ( sock_send(sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
		goto error;

	if (!serveropen_dp)
	{
	SOCKET socktemp;	// We need another socket, since we're going to accept() a connection

		// Connection creation
		saddrlen = sizeof(struct sockaddr_storage);

		socktemp= accept(sockdata, (struct sockaddr *) &saddr, &saddrlen);
		
		if (socktemp == -1)
		{
			sock_geterror("accept(): ", errbuf, PCAP_ERRBUF_SIZE);
			goto error;
		}

		// Now that I accepted the connection, the server socket is no longer needed
		sock_close(sockdata, errbuf, PCAP_ERRBUF_SIZE);
		sockdata= socktemp;
	}

	fp->rmt_sockdata= sockdata;

	/* GV we need this to create the thread as detached. */
	/* GV otherwise, the thread handle is not destroyed  */
	pthread_attr_init(&detachedAttribute); 
	pthread_attr_setdetachstate(&detachedAttribute, PTHREAD_CREATE_DETACHED);
	
	// Now we have to create a new thread to receive packets
	if ( pthread_create(threaddata, &detachedAttribute, (void *) daemon_thrdatamain, (void *) fp) )
	{
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error creating the data thread");
		pthread_attr_destroy(&detachedAttribute);
		goto error;
	}

	pthread_attr_destroy(&detachedAttribute);
	// Check if all the data has been read; if not, discard the data in excess
	if (nread != plen)
		sock_discard(sockctrl, plen - nread, NULL, 0);

	return fp;

error:
	rpcap_senderror(sockctrl, errbuf, PCAP_ERR_STARTCAPTURE, NULL);

	if (addrinfo)
		freeaddrinfo(addrinfo);

	if (threaddata)
		pthread_cancel(*threaddata);

	if (sockdata)
		sock_close(sockdata, NULL, 0);

	// Check if all the data has been read; if not, discard the data in excess
	if (nread != plen)
		sock_discard(sockctrl, plen - nread, NULL, 0);

	if (fp)
	{
		pcap_close(fp);
		fp= NULL;
	}

	return NULL;
}
开发者ID:Jumbo88888,项目名称:rpcapd-linux,代码行数:101,代码来源:daemon.c

示例5: recv_packet


//.........这里部分代码省略.........

			if (send_message(lc_s, MSG_READY, MSG_STATUS_ERROR, NULL, 0) < 0) {
				ERR("cant send message ready error");
			}
			terminate("cant compile pcap filter");
		}

		if (pcap_setfilter(pdev, &filter) < 0) {
			ERR("error setting compiled filter: %s", pcap_geterr(pdev));

			if (send_message(lc_s, MSG_READY, MSG_STATUS_ERROR, NULL, 0) < 0) {
				ERR("cant send message ready error");
			}
			terminate("cant set compiled pcap filter");
		}

		pcap_freecode(&filter);

		if (s->ss->ret_layers > 0) {
			DBG(M_IPC, "returning whole packet via ipc");
		}

		DBG(M_IPC, "sending ready message to parent");

		if (pcap_setnonblock(pdev, 1, errbuf) < 0) {
			terminate("cant set pcap non-blocking mode");
		}

		if (send_message(lc_s, MSG_READY, MSG_STATUS_OK, NULL, 0) < 0) {
			terminate("cant send message ready");
		}

		while (1) {
			spdf[0].fd=lc_s;
			spdf[1].fd=pcap_fd;

			/* if pdev is a socket  ( ! -1 ) */
			if (xpoll(&spdf[0], 2, -1) < 0) {
				ERR("xpoll fails: %s", strerror(errno));
			}

			if (spdf[1].rw & XPOLL_READABLE) {
				pcap_dispatch(pdev, 1, parse_packet, NULL);
			}

			/* no packets, better drain the queue */
			drain_pqueue();

			if (spdf[0].rw & XPOLL_READABLE) {
				if (get_singlemessage(lc_s, &msg_type, &status, &ptr, &msg_len) != 1) {
					ERR("unexpected sequence of messages from parent in main read loop, exiting");
					worktodo=0;
					break;
				}

				if (msg_type == MSG_TERMINATE) {
					DBG(M_IPC, "parent wants me to stop listening, breaking");
					break;
				}
				else if (msg_type == MSG_QUIT) {
					DBG(M_IPC, "Parent wants me to quit, breaking");
					worktodo=0;
					break;
				}
				else {
					ERR("got strange message `%s' from parent, exiting", strmsgtype(msg_type));
					worktodo=0;
					break;
				}
			}
		}

		memset(&recv_stats, 0, sizeof(recv_stats));

		if (pcap_stats(pdev, &pcs) != -1) {

			recv_stats.packets_recv=pcs.ps_recv;
			recv_stats.packets_dropped=pcs.ps_drop;
			recv_stats.packets_dropped=pcs.ps_ifdrop;
		}

		if (send_message(lc_s, MSG_WORKDONE, MSG_STATUS_OK, (void *)&recv_stats, sizeof(recv_stats)) < 0) {
			terminate("cant send workdone message to parent, exiting");
		}

	} while (worktodo);

	pcap_close(pdev);
	if (s->pcap_dumpfile) {
		pcap_dump_close(pdump);
	}


	DBG(M_CLD, "listener exiting");

	shutdown(lc_s, SHUT_RDWR);
	close(lc_s);
 
	uexit(0);
}
开发者ID:IFGHou,项目名称:Unicornscan,代码行数:101,代码来源:recv_packet.c

示例6: main


//.........这里部分代码省略.........
		return -1;
	}
	conn_max = atoi(config_get_option(conf, MAIN_NAME, "max_connection_pool"));

	if (!config_get_option(conf, MAIN_NAME, "flow_timeout")) {
		msg(MSG_ERROR, "main: \"flow_timeout\" missing in section %s", MAIN_NAME);
		return -1;
	}
	flow_timeout = atoi(config_get_option(conf, MAIN_NAME, "flow_timeout"));

	connection_init_pool(conn_no, conn_max, flow_timeout);


	struct packet_pool* packet_pool = packet_pool_init(packet_pool_size, snaplen);
	struct thread_data worker_data;
	worker_data.pool = packet_pool;
	worker_data.dumpers = &dumps;

	pcap_t* pfile;
	if (pcap_file) { 
		pfile = open_pcap(pcap_file, 0, snaplen); 
		dumpers_create_all(&dumps, conf, pcap_datalink(pfile), snaplen);
		if (!dumps.count) {
			msg(MSG_FATAL, "Could not configure any modules.");
			return -1;
		}
		if (pthread_create(&worker_id, NULL, worker_thread, &worker_data)) {
			msg(MSG_FATAL, "Could not create worker thread: %s", strerror(errno));
			return -1;
		}
	} else {
		is_live = 1;
		pfile = open_pcap(capture_interface, 1, snaplen);
		dumpers_create_all(&dumps, conf, pcap_datalink(pfile), snaplen);
		if (!dumps.count) {
			msg(MSG_FATAL, "Could not configure any modules.");
			return -1;
		}
		// the dumper creating can take a significant amount of time.
		// We could not read any packets during this initialization phase and 
		// could therefore drop a significant amount of packets (depending on
		// the link speed). We therefore close and reopen the pcap descriptor
		// in order to reset the statistics and get more accurate packet
		// drop statistice (we had to open the pcap interface for retrieving the
		// interface link type which is important for module initialization
		pcap_close(pfile);
		if (pthread_create(&worker_id, NULL, worker_thread, &worker_data)) {
			msg(MSG_FATAL, "Could not create worker thread: %s", strerror(errno));
			return -1;
		}
		pfile = open_pcap(capture_interface, 1, snaplen);
	}
	msg(MSG_INFO, "%s is up and running. Starting to consume packets ...", argv[0]);

	struct pcap_pkthdr pcap_hdr;
	time_t last_stats = 0;
	time_t stats_interval = 10;
	uint64_t captured = 0;
	const unsigned char* data = NULL;
	while (running) {
		if (NULL != (data = pcap_next(pfile, &pcap_hdr))) {
			captured++;
			if (print_stats_enabled) {
				if (pcap_hdr.ts.tv_sec - last_stats > stats_interval && is_live) {
					last_stats = pcap_hdr.ts.tv_sec;
					print_stats(pfile, captured, packet_pool);
				}
			}
			packet_new(packet_pool, &pcap_hdr, data);
		} else {
			if (!is_live)
				running = 0;
		}
	}

	msg(MSG_INFO, "%s finished reading packets ...", argv[0]);

	// TODO: this is a hack! we might need to wake the worker thread
	// because it might be blocked at a mutex waiting for new packets
	// we have to insert a packet in order to wake the thread from the 
	// mutex. Hence, we re-include the last packet into the pool again ...
	// FIXME: The hack can result in a segmentation fault if no packet
	// has been read from the pcap_t ...
	unsigned char* useless = malloc(snaplen);
	packet_new(packet_pool, &pcap_hdr, useless);
	free(useless);
	pthread_join(worker_id, NULL);

	// ok, the second worker is stopped right now
	// we are therefore the only thread that works on the connection pool.
	// lets timeout all active connnections to update the statistics (e.g. for stats_module)
	connection_flush_all_active_conns();

	dumpers_finish(&dumps);
	connection_deinit_pool();
	packet_pool_deinit(packet_pool);
	config_free(conf);

	return 0;
}
开发者ID:OurLuckyProjects,项目名称:pcapsplit,代码行数:101,代码来源:main.c

示例7: main

int main(int argc, char **argv)
{
	int i,j,src;
	int max;
	int min;
	float avg,sum;
	unsigned int pkt_counter=0;   // packet counter
	unsigned long byte_counter=0; //total bytes seen in entire trace
	unsigned long cur_counter=0; //counter for current 1-second interval
	unsigned long max_volume = 0;  //max value of bytes in one-second interval
	unsigned long current_ts=0;
	struct pcap_pkthdr header;

	if (argc < 2)
	{
	fprintf(stderr, "Usage: %s [input pcaps]\n", argv[0]);
	exit(1);
	}
	pcap_t *handle;
	char errbuf[PCAP_ERRBUF_SIZE];
	handle = pcap_open_offline(argv[1], errbuf);
	if (handle == NULL)
	{
	fprintf(stderr,"Couldn't open pcap file %s: %s\n", argv[1], errbuf);
	return(2);
	}
	if (pcap_datalink(handle) != DLT_EN10MB) {
		printf("this is not an Ethernet\n");
		exit(EXIT_FAILURE);
	}

	/*if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1)
	{
		fprintf(stderr, "Couldn't parse filter %s: %s\n",
		    filter_exp, pcap_geterr(handle));
		exit(EXIT_FAILURE);
	}
	if (pcap_setfilter(handle, &fp) == -1) {
		fprintf(stderr, "Couldn't install filter %s: %s\n",
		    filter_exp, pcap_geterr(handle));
		exit(EXIT_FAILURE);
	}*/
	//u_char *user = "the message ";
		ip_des_list = fopen("ipdes.txt","w");
		ip_src_list = fopen("ipsrc.txt","w");
		eth_src_list = fopen("ethsrc.txt","w");
		eth_des_list = fopen("ethdes.txt","w");
		tcp_port_src_list = fopen("tcp_port_src.txt","w");
		tcp_port_des_list = fopen("tcp_port_des.txt","w");
		udp_port_src_list = fopen("udp_port_src.txt","w");
		udp_port_des_list = fopen("udp_port_des.txt","w");

		pcap_loop(handle, 0, packet_handler, NULL);
		pcap_close(handle);
		FILE *ip_des_read, *ip_src_read, *eth_src_read, *eth_des_read;
		FILE *tcp_port_src_read, *tcp_port_des_read, *udp_port_src_read, *udp_port_des_read;
		fclose(ip_des_list);
		fclose(ip_src_list);
		fclose(eth_src_list);
		fclose(tcp_port_src_list);
		fclose(tcp_port_des_list);
		fclose(udp_port_src_list);
		fclose(udp_port_des_list);

	printf("\n  Ethernet Source     \t\tCount\n");
		eth_src_read = fopen("ethsrc.txt","r");
		PrintIpCount(eth_src_read);        //Calling the function to print Source Ethernet addresses count
		fclose(eth_src_read);

	printf("\n  Ethernet Destination     \tCount\n");
		eth_des_read = fopen("ethdes.txt","r");
		PrintIpCount(eth_des_read);        //Calling the function to print Destination Ethernet addresses count
		fclose(eth_des_read);


	printf("\n  Source IP address     \tCount\n");
		ip_src_read = fopen("ipsrc.txt","r");
		PrintIpCount(ip_src_read);    //Calling the function to print Source IP addresses count
		fclose(ip_src_read);

	printf("\n  Destination IP address     \tCount\n");
		ip_des_read = fopen("ipdes.txt","r");
		PrintIpCount(ip_des_read);        //Calling the function to print Destination IP addresses count
	fclose(ip_des_read);

	printf("\n  TCP Source Port Address     \tCount\n");
		tcp_port_src_read = fopen("tcp_port_src.txt","r");
		PrintIpCount(tcp_port_src_read);
		fclose(tcp_port_src_read);

	printf("\n  TCP Destination Port Address  Count\n");
		tcp_port_des_read = fopen("tcp_port_des.txt","r");
		PrintIpCount(tcp_port_des_read);
		fclose(tcp_port_des_read);

	printf("\n  UDP Source Port Address     \tCount\n");
		udp_port_src_read = fopen("udp_port_src.txt","r");
		PrintIpCount(udp_port_src_read);
		fclose(udp_port_src_read);

//.........这里部分代码省略.........
开发者ID:magevadi,项目名称:masters-class-projects,代码行数:101,代码来源:with_check_eth_display_siva_sent.c

示例8: StartClient


//.........这里部分代码省略.........
	
	//IPv4
	/* Need to improve , auto bind the bond0 */
	client_addr.sin_family = AF_INET;
	client_addr.sin_addr.s_addr = inet_addr(BindIP); 
	client_addr.sin_port = htons(0);
	
	//Create TCP socket
	
    if( client_socket < 0)
    {
        printf("Create Socket Failed!\n");
        exit(1);
    }
	
	//Bind the Socket with Struct
    if( bind(client_socket,(struct sockaddr*)&client_addr,sizeof(client_addr)))
    {
        printf("Client Bind Port Failed!\n");
        exit(1);
    }
	
	//Define the Server socket for comm
	struct sockaddr_in server_addr;
    bzero(&server_addr,sizeof(server_addr));
    server_addr.sin_family = AF_INET;
	
    if(inet_aton(ServIP,&server_addr.sin_addr) == 0) 
	
    {
        printf("Server IP Address Error!\n");
        exit(1);
    }
	server_addr.sin_port = htons(SERVER_PORT);
    socklen_t server_addr_length = sizeof(server_addr);
	    
	/*--------------------------------*/
	
	//Connect to the Server
	if(connect(client_socket,(struct sockaddr*)&server_addr, server_addr_length) < 0)
    {
        printf("Can Not Connect To Server!\n");
        exit(1);
    }
	
      /* get network number and mask associated with capture device */
    if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
        fprintf(stderr, "Couldn't get netmask for device %s: %s\n",
         dev, errbuf);
        net = 0;
        mask = 0;
    }


    /* print capture info */
    //printf("Device: %s\n", dev);
    //printf("Number of packets: %d\n", num_packets);
    //printf("Filter expression: %s\n", filter_exp);
	int rc =0;

	
	handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
    if (handle == NULL) {
        fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
        exit(EXIT_FAILURE);
    }

    /* compile the filter expression */
    if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
        fprintf(stderr, "Couldn't parse filter %s: %s\n",
         filter_exp, pcap_geterr(handle));
        exit(EXIT_FAILURE);
    }


    /* apply the compiled filter */
    if (pcap_setfilter(handle, &fp) == -1) {
        fprintf(stderr, "Couldn't install filter %s: %s\n",
         filter_exp, pcap_geterr(handle));
        exit(EXIT_FAILURE);
    }
	printf("Initial Interface for CAP ...OK\n");
	
	printf("Callback func starting...\n"); 
    /* now we can set our callback function */

	pcap_loop(handle, num_packets, got_packet, (u_char *)&client_socket);


    /* cleanup */
    pcap_freecode(&fp);
    pcap_close(handle);


    printf("\nCapture complete.\n");
	printf("Done\n");


return rc;
}
开发者ID:ShifengH,项目名称:TraceLdap,代码行数:101,代码来源:StartClient.c

示例9: terminate

void terminate()
{
	pcap_close(p);	
}
开发者ID:BackupTheBerlios,项目名称:monitoringapi,代码行数:4,代码来源:pcap_test.c

示例10: restruct_pkt

/*
 * func: 	restruct a new udp package.
 * param: 	
 * return: 	0 success; -1 fail
 */
int restruct_pkt(char *buf, 
        struct eth_hdr *pethh, 
        struct ip_hdr *piph, int iph_len, 
        struct udp_hdr *pudph,
        uint32_t multi_ip,
        uint16_t multi_port)
{
    char errbuf[PCAP_ERRBUF_SIZE] = {0};
   // char * device = "eth0";
    char device [DEV_BUF_SIZE];
    pcap_t *adhandle = NULL;
    int ret;

    char *str_dev = get_dev_name(piph->ip_destaddr, device);
    if(str_dev == NULL)
    {
        fprintf(gfp_log, "[%s:%d]get_dev_name is null!\n", __FILE__, __LINE__);
        fflush(gfp_log);
        return -1;
    }
    if((adhandle = pcap_open_live(device, 0x10000, PCAP_OPENFLAG_PROMISCUOUS, 1000,  errbuf)) == NULL)
    {
        fprintf(gfp_log, "[%s:%d][pcap_open_live error] : %s\n", __FILE__, __LINE__, errbuf);
        fflush(gfp_log);
        return -1;
    }

    pethh->ether_dhost[0] = 0x01;
    pethh->ether_dhost[1] = 0x00;
    pethh->ether_dhost[2] = 0x5e;
    pethh->ether_dhost[3] = (unsigned char)((multi_ip  >> 8) & 0x7F);;
    pethh->ether_dhost[4] = (unsigned char)((multi_ip >> 16) & 0xFF);;
    pethh->ether_dhost[5] = (unsigned char)((multi_ip >> 24) & 0xFF);;
//AC:85:3D:AF:C7:08
    pethh->ether_shost[0] = 0x00;
    pethh->ether_shost[1] = 0x16;
    pethh->ether_shost[2] = 0x3e;
    pethh->ether_shost[3] = 0x00;
    pethh->ether_shost[4] = 0x04;
    pethh->ether_shost[5] = 0x0e;

    pethh->ether_type = htons(ETHERTYPE_IP);

    if((sizeof(struct ip_hdr) % 4) != 0)
    {
        fprintf(gfp_log, "[%s:%d][IP Header error]\n", __FILE__, __LINE__);
        fflush(gfp_log);
        pcap_close(adhandle);
        return -1;
    }
    uint16_t ip_len = ntohs(piph->ip_totallength);
    uint16_t udp_len = htons(pudph->udp_length);

    piph->ip_tos = 0;
    piph->ip_id = htons(0x0000);
    piph->ip_offset = htons(0x4000);
    piph->ip_ttl = 0x20;
    piph->ip_checksum = 0;
    piph->ip_destaddr = multi_ip;
    piph->ip_totallength = htons(ip_len); 
    piph->ip_checksum  = checksum((uint16_t *)piph, iph_len);

    pudph->dest_portno = htons(multi_port);
    pudph->src_portno = htons(52540);
    pudph->udp_checksum = 0;
    pudph->udp_length = htons(udp_len);
    pudph->udp_checksum = udp_checksum(piph, iph_len, udp_len);
    //pudph->udp_checksum = htons(0x16ed);
    //////just for test printf
    //printf("rebuild multicast package: \n");
    //printf("   src : %s" , inet_ntoa(*((struct in_addr *)(&piph->ip_srcaddr))));
    //printf("   dst : %s\n" , inet_ntoa(*((struct in_addr *)(&piph->ip_destaddr))));
    ///////////////////////////////////////////////////
    int pkt_len = ip_len + ETHER_HEADER_SIZE;

    /* just print the pkt info */
    /*
    int i=0;
    for(i = 0 ; i != sizeof(struct ip_hdr); i++)
    {
        printf("%02x ",(*((char *)piph+i))&0xff);
    }
    */
    //printf("pkt len %u\n", pkt_len);
    ret = write(tun, piph, ip_len);
    if(pcap_sendpacket(adhandle, (const u_char*)buf, pkt_len) == -1)
    {
        fprintf(gfp_log, "[%s:%d][pcap_sendpacket error]\n", __FILE__, __LINE__);
        fflush(gfp_log);
        pcap_close(adhandle);
        return -1;
    }
    else
    {
     //   printf("=====send a pkt!\n");
//.........这里部分代码省略.........
开发者ID:sunadm,项目名称:multicast_proxy,代码行数:101,代码来源:handleData.c

示例11: restruct_pkt_others_proto

/*
 * func: 	restruct a new others proto package.
 * param: 	
 * return: 	0 success; -1 fail
 */
int restruct_pkt_others_proto(char *buf, 
        struct eth_hdr *pethh, 
        struct ip_hdr *piph, int iph_len, 
        struct udp_hdr *pudph,
        uint32_t multi_ip,
        uint16_t multi_port)
{
    char errbuf[PCAP_ERRBUF_SIZE] = {0};
    char * device = "eth0";
    pcap_t *adhandle = NULL;

    if((adhandle = pcap_open_live(device, 0x10000, PCAP_OPENFLAG_PROMISCUOUS, 1000, errbuf)) == NULL)
    {
        fprintf(gfp_log, "[%s:%d][pcap_open_live error] : %s\n", __FILE__, __LINE__, errbuf);
        fflush(gfp_log);
        return -1;
    }

    pethh->ether_dhost[0] = 0x01;
    pethh->ether_dhost[1] = 0x00;
    pethh->ether_dhost[2] = 0x5e;
    pethh->ether_dhost[3] = 0x7e;
    pethh->ether_dhost[4] = 0x01;
    pethh->ether_dhost[5] = 0x02;

    pethh->ether_shost[0] = 0x00;
    pethh->ether_shost[1] = 0x16;
    pethh->ether_shost[2] = 0x3e;
    pethh->ether_shost[3] = 0x00;
    pethh->ether_shost[4] = 0x04;
    pethh->ether_shost[5] = 0x0e;

    pethh->ether_type = htons(ETHERTYPE_IP);

    if((sizeof(struct ip_hdr) % 4) != 0)
    {
        fprintf(gfp_log, "[%s:%d][IP Header error]\n", __FILE__, __LINE__);
        pcap_close(adhandle);
        return -1;
    }

    uint16_t ip_len = ntohs(piph->ip_totallength);

    piph->ip_tos = 0;
    piph->ip_id = htons(0x1000);
    piph->ip_offset = htons(0x0040);
    piph->ip_ttl = 0x80;
    piph->ip_checksum = 0;
    piph->ip_destaddr = multi_ip;
    piph->ip_totallength = htons(ip_len); 
    piph->ip_checksum = checksum((u_int16_t*)piph, iph_len);


    int pkt_len = ip_len + ETHER_HEADER_SIZE;
    if(pcap_sendpacket(adhandle, (const u_char*)buf, pkt_len) == -1)
    {
        fprintf(gfp_log, "[%s:%d][pcap_sendpacket error]\n", __FILE__, __LINE__);
        fflush(gfp_log);
        pcap_close(adhandle);
        return -1;
    }
    pcap_close(adhandle);
    return 0;
}
开发者ID:sunadm,项目名称:multicast_proxy,代码行数:69,代码来源:handleData.c

示例12: main


//.........这里部分代码省略.........
      return -1;
    }

  signal (SIGINT, on_ctrl_c);

  /* Announce */
  printf ("%s: requested to open #%d pcap-handle%s\n", progname, handles, handles > 1 ? "s" : "");

  /* Allocate enough memory to keep the pointers to the pcap-handle(s) */
  table = calloc ((handles + 1) * sizeof (pcap_t *), 1);
  for (p = 0; p < handles; p ++)
    table [p] = NULL;
  table [p] = NULL;

  /* Open the interface for packet capturing */
  for (p = 0; p < handles; p ++)
    if (! (table [p] = pcap_open_live (interface, snapshot, promiscuous, 1000, ebuf)))
      {
	printf ("%s: cannot open interface '%s' due to '%s'\n", progname, interface, ebuf);
	return -1;
      }

  printf ("%s: listening from %s using %s\n\n", progname, interface, pcap_lib_version ());

  /* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

  if (hb == -1)
    hb = maxcount / DEFAULT_HB;
  if (! hb)
    hb = 1;

  printf ("%s: starting to capture #%lu pckts using #%d pcap-handle%s...\n", progname, maxcount, handles, handles > 1 ? "s" : "");

  gettimeofday (& started, NULL);

  p = 0;
  while (! maxcount || (partial + errors) < maxcount)
    {
      /* Please give me just a packet at once from the interface */
      if ((packet = pcap_next (table [p], & header)))
	{
	  partial ++;
	  if (! quiet)
	    {
	      if (! (partial % hb))
		{
		  static unsigned long previous = 0;
		  static struct timeval latest;

		  struct timeval now;

		  /* Show pkts/secs in the latest period */
		  gettimeofday (& now, NULL);
		  delta = delta_time_in_milliseconds (& now, & latest);

		  printf ("%s: pkts rcvd #%lu of #%lu %s", progname, partial, maxcount, percentage (partial, maxcount));
		  if (previous && delta)
		    printf (" [%8.2f pkts/sec => +%lu pkts in %s]",
			    (double) (partial - previous) * 1000 / delta,
			    partial - previous, elapsed_time (& latest, & now));
		  printf ("\n");

		  previous = partial;
		  latest = now;
		}
	      else
		showbar (partial);
	    }
	}
      else
	errors ++;

      /* Round-robin to choose the pcap-handle candidate for the packet capture */
      p = (p + 1) % handles;
    }

  /* Close the pcap-handle(s) */
  for (p = 0; p < handles; p ++)
    pcap_close (table [p]);
  free (table);

  gettimeofday (& stopped, NULL);
  delta = (double) delta_time_in_milliseconds (& stopped, & started);

  printf ("              \n");

  printf ("Time:\n");
  printf ("=====\n");
  print_time_in_secs (& started, "Started:       ");
  print_time_in_secs (& stopped, "Finished:      ");
  printf ("Elapsed Time:  %s\n", elapsed_time (& started, & stopped));
  printf ("\n");

  /* Print out test results */
  printf ("Great Totals:\n");
  printf ("=============\n");
  printf ("pkts rcvd #%lu pckts of #%lu => %7.2f pkts/sec\n", partial, maxcount, (double) partial * 1000 / delta);

  return 0;
}
开发者ID:kingyueyang,项目名称:network_flow_monitor,代码行数:101,代码来源:pcaps.c

示例13: main

main(int argc, char *argv[])
{
    int   len;
    char *infile;
    char *conn_name;
    int  lineno=0;
    struct connection *c1;
    pcap_t *pt;
    char   eb1[256];

    EF_PROTECT_BELOW=1;
    EF_PROTECT_FREE=1;
    EF_FREE_WIPES  =1;

    progname = argv[0];
    leak_detective = 1;

    init_crypto();

    if(argc != 4) {
	fprintf(stderr, "Usage: %s <whackrecord> <conn-name> <pcapin>\n", progname);
	exit(10);
    }
    /* argv[1] == "-r" */

    tool_init_log();
    init_fake_vendorid();
    
    infile = argv[1];
    conn_name = argv[2];

    readwhackmsg(infile);

    send_packet_setup_pcap("parentR1.pcap");
 
    c1 = con_by_name(conn_name, TRUE);

    show_one_connection(c1);
    cur_debugging = DBG_EMITTING|DBG_CONTROL|DBG_CONTROLMORE;

    pt = pcap_open_offline(argv[3], eb1);
    if(!pt) {
	perror(argv[3]);
	exit(50);
    }
    pcap_dispatch(pt, 1, recv_pcap_packet, NULL);
    pcap_close(pt);

    /* read same packet from network again, to see what we will do */
    pt = pcap_open_offline(argv[3], eb1);
    if(!pt) {
	perror(argv[3]);
	exit(50);
    }

    pcap_dispatch(pt, 1, recv_pcap_packet, NULL);
    pcap_close(pt);

    show_states_status();

    {
	struct state *st;

	/* find st involved */
	st = state_with_serialno(1);
	delete_state(st);
    }

    report_leaks();

    tool_close_log();
    exit(0);
}
开发者ID:st3fan,项目名称:libreswan,代码行数:73,代码来源:parentR1duplicate.c

示例14: pcap_io_init

int pcap_io_init(char *adapter)
{
	int dlt;
	char *dlt_name;
	emu_printf("Opening adapter '%s'...",adapter);
	u16 checksum;
	GetMACAddress(adapter,&host_mac);
	
	//Near copy of the host mac, butchered slightly, should be pretty good!
	eeprom[0] = host_mac.bytes[0];
	eeprom[1] = host_mac.bytes[1];
	eeprom[2] = host_mac.bytes[2];
	eeprom[3] = host_mac.bytes[2];
	eeprom[4] = host_mac.bytes[5];
	eeprom[5] = host_mac.bytes[4];

	//The checksum seems to be all the values of the mac added up in 16bit chunks
	checksum = dev9.eeprom[0] + dev9.eeprom[1] + dev9.eeprom[2] & 0xffff;

	dev9.eeprom[3] = checksum;

	//emu_printf("eeprom Mac set to %x %x %x %x %x %x", eeprom[0], eeprom[1], eeprom[2], eeprom[3], eeprom[4], eeprom[5]);
	//emu_printf("Checksum %x %x", eeprom[6], eeprom[7]);
	
	/* Open the adapter */
	if ((adhandle= pcap_open_live(adapter,	// 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_mode==switched?1:0,				// promiscuous mode (nonzero means promiscuous)
							 1,			// read timeout
							 errbuf			// error buffer
							 )) == NULL)
	{
		fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", adapter);
		return -1;
	}

	dlt = pcap_datalink(adhandle);
	dlt_name = (char*)pcap_datalink_val_to_name(dlt);

	fprintf(stderr,"Device uses DLT %d: %s\n",dlt,dlt_name);
	switch(dlt)
	{
	case DLT_EN10MB :
	//case DLT_IEEE802_11:
		break;
	default:
		SysMessage("ERROR: Unsupported DataLink Type (%d): %s",dlt,dlt_name);
		pcap_close(adhandle);
		return -1;
	}

	if(pcap_setnonblock(adhandle,1,errbuf)==-1)
	{
		fprintf(stderr,"WARNING: Error setting non-blocking mode. Default mode will be used.\n");
	}

	//Changing the LogSetting might not affect logging
	//directory of winPcap logs if done after Open()
	const std::string pfile(s_strLogPath + "/packet.log");
	packet_log = fopen(pfile.c_str(), "w");

	const std::string plfile(s_strLogPath + "/pkt_log.pcap");
	dump_pcap = pcap_dump_open(adhandle, plfile.c_str());

	pcap_io_running=1;
	emu_printf("Ok.\n");
	return 0;
}
开发者ID:auronx223,项目名称:pcsx2,代码行数:69,代码来源:pcap_io.cpp

示例15: pcap_close

Injector::~Injector()
{
	if( handle_ )
		pcap_close(handle_);
}
开发者ID:MuminSalimov,项目名称:packet-manipulation-library,代码行数:5,代码来源:injector.cpp


注:本文中的pcap_close函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。