I am trying to find the easiest way to intercept TCP SYN packets sent by my computer in a c++ program. There are couple of options that I know. One would be monitor all traffic
If you merely want to see the packets, use libpcap
and packet filtering - that'll work on most any UNIX variant.
If you want to somehow intercept and rewrite the packets, please supply more information about what you're trying to do, and what's supposed to happen to the packets afterwards.
As you suggest, that might be an application for netfilter and its queue module, although that requires a 2.6.14 or later kernel:
Main Features
- receiving queued packets from the kernel nfnetlink_queue subsystem
- issuing verdicts and/or reinjecting altered packets to the kernel nfnetlink_queue subsystem
You can use the raw sockets or for example the pcap library. With pcap you set up the filter and capture the interesting traffic:
#include <pcap.h>
...
pcap_t* reader_handle;
char errbuf[PCAP_ERRBUF_SIZE];
if ( (reader_handle = pcap_open_live(device_string, capture_size, 0, timeout, errbuf) ) == NULL)
{
//ooops
}
struct bpf_program fp;
if (pcap_compile(reader_handle, &fp, filter_string, 1, 0) == -1)
{
//ooops, cleanup
}
if (pcap_setfilter(reader_handle, &fp) == -1)
{
//ooops, cleanup
}
pcap_freecode(&fp);
And afterwards you just capture, there are few different ways, for example:
pcap_pkthdr* header;
u_char* pkt_data;
const int status = pcap_next_ex(reader_handle, &header, &pkt_data);
// Check the status
After ending the capture:
pcap_close(reader_handle);
You need privileges to play with raw sockets. The above example can be nicely wrapped in C++.