I want to monitor packets on specific ports in Mac OS X. Being able to read their contents and sometimes changing their contents (if possible). I was wondering if it's possible by writing a KEXT or can I do this in an application and showing results instantly. I would appreciate any information on libraries and approaches I can use to achieve this.
"Monitor packets" in what sense?
If you mean "watch what packets to or from specific TCP or UDP ports are sent" or "what packets are sent or received on particular network interfaces", you would use the pcap library, just as on other UN*Xes. libpcap/WinPcap is the library that Wireshark - and tcpdump - use; on OS X, the underlying kernel mechanism it uses is BPF (the Berkeley Packet Filter), which is built into XNU (it is open-source - see the bsd/net/bpf.c
and bsd/net/bpf_filter.c
files, and the header files they include, in the XNU source) and doesn't require a kext. (Wireshark does not have its own kext; it uses libpcap/WinPcap so that it can work on Linux and OS X and *BSD and Solaris and HP-UX and AIX and Tru64 UNIX and IRIX and so on, as well as on Windows if WinPcap is installed, so, on OS X and *BSD, it ultimately uses BPF.)
Libpcap/WinPcap doesn't, except on Linux, allow you to capture on all interfaces with one "handle"; you would have to use pcap_findalldevs()
to find all the currently-available interfaces, and then open separate handles for each of them. If by "ports" you mean "network ports", so that one "port" is your Ethernet port and another is your Wi-Fi adapter, you'd have to individually open all the "ports" on which you want to capture.
If by "ports" you mean TCP or UDP ports, and you only want to watch traffic to or from particular ports, you'd have to specify a "filter" expression, translate it to "BPF code" with pcap_compile()
, and then make it the filter for a particular libpcap/WinPcap handle with pcap_setfilter()
.
If you want to use a Cocoa wrapper for pcap, a Google search I did a while ago found packetsniffer and CapKit; I have not used either of those, so I can't recommend one or the other.