Skip to content

Instantly share code, notes, and snippets.

@heltonmarx
Created February 24, 2016 03:05
Show Gist options
  • Save heltonmarx/8058bfb9103876409236 to your computer and use it in GitHub Desktop.
Save heltonmarx/8058bfb9103876409236 to your computer and use it in GitHub Desktop.
Sniffer tcp packages on port 7000 using libpcap
#include <pcap.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#define MAXBYTES2CAPTURE 2048
/* processPacket(): Callback function called by pcap_loop() everytime a packet */
/* arrives to the network card. This function prints the captured raw data in */
/* hexadecimal. */
void processPacket(u_char *arg, const struct pcap_pkthdr* pkthdr, const u_char * packet)
{
int i=0, *counter = (int *)arg;
printf("Packet Count: %d\n", ++(*counter));
printf("Received Packet Size: %d\n", pkthdr->len);
printf("Payload:\n");
for (i=0; i < (int)pkthdr->len; i++) {
/* If it is a printable character, print it */
if ( isprint(packet[i]) ) {
printf("%c ", packet[i]);
} else {
printf(". ");
}
if( (i % 32 == 0 && i != 0) || i == (int)(pkthdr->len-1)) {
printf("\n");
}
}
}
/* main(): Main function. Opens network interface and calls pcap_loop() */
int main(int argc, char *argv[])
{
int count=0;
pcap_t *descr = NULL;
char errbuf[PCAP_ERRBUF_SIZE], *device=NULL;
char filter_exp[] = {"tcp port 7000"};
bpf_u_int32 mask; /* Our netmask */
bpf_u_int32 net; /* Our IP */
struct bpf_program fp; /* The compiled filter */
memset(errbuf,0,PCAP_ERRBUF_SIZE);
if(argc > 1) { /* If user supplied interface name, use it. */
device = argv[1];
} else if ((device = pcap_lookupdev(errbuf)) == NULL) { /* Get the name of the first device suitable for capture */
fprintf(stderr, "ERROR: %s\n", errbuf);
return -1;
}
/* Find the properties for the device */
net = mask = 0;
if (pcap_lookupnet(device, &net, &mask, errbuf) == -1) {
fprintf(stderr, "Couldn't get netmask for device %s: %s\n", device, errbuf);
}
printf("Opening device %s\n", device);
printf("Filter expression: %s\n", filter_exp);
/* Open device in promiscuous mode */
if ((descr = pcap_open_live(device, MAXBYTES2CAPTURE, 1, 512, errbuf)) == NULL) {
fprintf(stderr, "ERROR: %s\n", errbuf);
return -1;
}
/* Compile and apply the filter */
if (pcap_compile(descr, &fp, filter_exp, 0, net) == -1) {
fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(descr));
return -1;
}
if (pcap_setfilter(descr, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(descr));
return -1;
}
/* Loop forever & call processPacket() for every received packet*/
if (pcap_loop(descr, -1, processPacket, (u_char *)&count) == -1) {
fprintf(stderr, "ERROR: %s\n", pcap_geterr(descr) );
return -1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment