Skip to content

Instantly share code, notes, and snippets.

@larsch
Last active January 11, 2022 08:14
Show Gist options
  • Save larsch/65a53ef780b17fd2d19295dcbb4e7fcf to your computer and use it in GitHub Desktop.
Save larsch/65a53ef780b17fd2d19295dcbb4e7fcf to your computer and use it in GitHub Desktop.
libpcap latency/break test
#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>
pcap_t* pcap;
void* thread(void* arg) {
(void)arg;
sleep(2);
kill(0, SIGALRM);
return NULL;
}
void handle_signal(int sig) {
pcap_breakloop(pcap);
fprintf(stderr, "handle signal %d\n", sig);
}
int main(int argc, char** argv) {
(void)argc;
(void)argv;
signal(SIGALRM, handle_signal);
char errbuf[PCAP_ERRBUF_SIZE];
#if 0
pcap = pcap_open_live("enp0s3", 1500, 1, 100, errbuf);
if (pcap == NULL) {
fprintf(stderr, "Failed to create pcap handle: %s\n", errbuf);
return EXIT_FAILURE;
}
#else
pcap = pcap_create("enp0s3", errbuf);
if (pcap == NULL) {
fprintf(stderr, "Failed to create pcap handle: %s\n", errbuf);
return EXIT_FAILURE;
}
pcap_set_immediate_mode(pcap, 1);
pcap_set_timeout(pcap, 100);
if (pcap_activate(pcap) != 0) {
fprintf(stderr, "Failed to activate pcap: %s\n", pcap_geterr(pcap));
pcap_close(pcap);
return EXIT_FAILURE;
}
#endif
struct pcap_pkthdr* pkt_header = NULL;
const u_char* pkt_data = NULL;
pthread_t thr;
pthread_create(&thr, NULL, &thread, NULL);
while (1) {
int res = pcap_next_ex(pcap, &pkt_header, &pkt_data);
if (res == 1) {
struct tm* tstm = gmtime(&pkt_header->ts.tv_sec);
char tmbuf[128];
strftime(tmbuf, sizeof tmbuf, "%Y-%m-%dT%H:%M:%S", tstm);
printf("%s.%06ld ", tmbuf, pkt_header->ts.tv_usec);
struct timeval nowtv;
gettimeofday(&nowtv, NULL);
tstm = gmtime(&nowtv.tv_sec);
strftime(tmbuf, sizeof tmbuf, "%Y-%m-%dT%H:%M:%S", tstm);
printf("%s.%06ld ", tmbuf, nowtv.tv_usec);
long secDelta = nowtv.tv_sec - pkt_header->ts.tv_sec;
long usecDelta = nowtv.tv_usec - pkt_header->ts.tv_usec;
double delta = secDelta + usecDelta / 1000000.0;
printf(" %.6f\n", delta);
}
else if (res == 0)
printf("pcap_next_ex timeout\n");
else if (res < 0) {
fprintf(stderr, "Failed to read: %d, %s\n", res, pcap_geterr(pcap));
pcap_close(pcap);
return EXIT_FAILURE;
} else {
printf("pcap_next_ex returned %d\n", res);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment