libpcap学习(一) 获取网卡列表

一、环境要求

      1.安装libpcap:

      在http://www.tcpdump.org/下载libpcap


./configure
make
sudo make install

       2.安装automake


apt-get install automake

apt-get install flex

apt-get install byacc

      关于automake用法请自行百度!

二、代码


1.Makefile.am

bin_PROGRAMS = netsniffer
LIBS += -L/usr/local/lib -lpthread -lpcap
netsniffer_SOURCES = netsniff.c

2.netsniff.c

#include "netsniff.h"
#include <pcap.h>
void main ()
{
        findAllDevs();
        printf("hi, shabi!~");
}

void findAllDevs()
{
        char errbuf[PCAP_ERRBUF_SIZE];
        int i = 0;
        pcap_if_t *d = NULL;
        if (pcap_findalldevs(&g_tbNetCardInfo, errbuf) == -1)//返回网卡列表,alldevs指向表头
        {
                fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
                return;
        }
        for(d = g_tbNetCardInfo; d; d = d->next)
        {
                printf("%d. %s", ++i, d->name);
                if (d->description)
                        printf(" (%s)\n", d->description);
                else
                        printf(" (No description available)\n");
        }

        if(i==0)
        {
                printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
                return;
        }


}
  


3.netsniff.h

#include <stdio.h>
#include <pcap.h>

pcap_if_t *g_tbNetCardInfo = NULL;

void main();
void findAllDevs();
void freeDevsTables();

将这三个文件放于同一个文件夹进行编译

你可能感兴趣的:(libpcap学习(一) 获取网卡列表)