これを行うのに最適な場所は、必要なコードを tcpdump ソースから抽出することです。これは、基本的に libpcap のハウツー ガイドとネットワークの紹介の両方を 1 つにまとめたものです。
とにかく、必要なのは、から収集したパケット処理関数ですpcap_open_live
。pcap_open_live
現在のスレッドが動作している間はブロックされるため、別のスレッドまたはプロセスを作成する必要もあります。
これで、パケット ハンドラー関数は次のようになります。
void packethandler( u_char *args, const struct pcap_pkthdr* pkthdr, const u_char* packet )
{
// ... allocs etc
// these instructions convert the "packet" string
// to a struct and determine it's type, a setting in
// the ethernet header.
eptr = (struct ether_header *) packet;
ether_type = ntohs(eptr->ether_type);
// ...
// these two functions extract the mac addresses
// into appropriately alloc'd strings.
// ether_ntoa converts the binary representation
// of the mac address into a string
snprintf(ethernet_shost, 20, "%s", ether_ntoa((struct ether_addr *)eptr->ether_shost));
snprintf(ethernet_dhost, 20, "%s", ether_ntoa((struct ether_addr *)eptr->ether_dhost));
// carry on...
}
これにより、MACアドレスが文字列として取得されます。ただし、ネットワーキングは簡単ではないことに注意してください。情報のバイナリ文字列、キャストなどで何をしているのかを知る必要があり、数値とオプションが何を意味するのかを知る必要があります。tcpdump ソースが複雑に見える場合は、ネットワークが複雑なためです。また、このプロセスを実現するために必要なヘッダーもリストしていません。そこには pcap チュートリアルがあります。時間をかけてそれらを読むことをお勧めします。私が単に答えを出すだけでは、ネットワーキングについて学ぶことはできません。
また、この機能は不完全です。ストレージ配列に適切な割り当てが必要になります (pcap は、後で抽出して戻すchar*
のではなく、使用したい C ライブラリです)。string
string