上文是假设当前进行live capture
那么接下来的代码是:
if (device == NULL){
device = pcap_lookupdev(ebuf);
if (device == NULL)
error("%s", ebuf);
}
这里看到了一个函数pcap_lookupdev,作用:pcap_lookupdev()来找网卡设备。
~~~~~~~~~~~~~~~~~~~~~
#ifdef WIN32
/*
* Print a message to the standard error on Windows.
* XXX - why do it here, with a different message?
*/
if(strlen(device) == 1) //we assume that an ASCII string is always longer than 1 char
{ //a Unicode string has a \0 as second byte (so strlen() is 1)
fprintf(stderr, "%s: listening on %ws\n", program_name, device);
}
else
{
fprintf(stderr, "%s: listening on %s\n", program_name, device);
}
fflush(stderr);
#endif /* WIN32 */
//windows环境下,不考虑这个代码
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pd = pcap_create(device, ebuf);
if (pd == NULL)
error("%s", ebuf);
//调用pcap_create()可以为一个活动的抓取器打开一个句柄
//自定义检查点: 1 2 3
//~~~~~~~~~~~~~~~~~~
/*
* Is this an interface that supports monitor mode?
*/
if (pcap_can_set_rfmon(pd) == 1)
supports_monitor_mode = 1;
else
supports_monitor_mode = 0;
//可以用于确定适配器是否可以进入监视模式
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
status = pcap_set_snaplen(pd, snaplen);
if (status != 0)
error("%s: Can't set snapshot length: %s",
device, pcap_statustostr(status));
//设置快照长度为65535
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
status = pcap_set_promisc(pd, !pflag);
if (status != 0)
error("%s: Can't set promiscuous mode: %s",
device, pcap_statustostr(status));
//设置混杂模式
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if (Iflag)
{
status = pcap_set_rfmon(pd, 1);
if (status != 0)
error("%s: Can't set monitor mode: %s",
device, pcap_statustostr(status));
}
//设置监视模式
status = pcap_set_timeout(pd, 1000);
if (status != 0)
error("%s: pcap_set_timeout failed: %s",
device, pcap_statustostr(status));
//设置超时时间
if (Bflag != 0)
{
status = pcap_set_buffer_size(pd, Bflag);
if (status != 0)
error("%s: Can't set buffer size: %s",
device, pcap_statustostr(status));
}
//设置缓冲区大小
status = pcap_activate(pd);
if (status < 0) {
/*
* pcap_activate() failed.
*/
cp = pcap_geterr(pd);
if (status == PCAP_ERROR)
error("%s", cp);
else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
status == PCAP_ERROR_PERM_DENIED) &&
*cp != '\0')
error("%s: %s\n(%s)", device,
pcap_statustostr(status), cp);
else
error("%s: %s", device,
pcap_statustostr(status));
} else if (status > 0) {
/*
* pcap_activate() succeeded, but it's warning us
* of a problem it had.
*/
cp = pcap_geterr(pd);
if (status == PCAP_WARNING)
warning("%s", cp);
else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
*cp != '\0')
warning("%s: %s\n(%s)", device,
pcap_statustostr(status), cp);
else
warning("%s: %s", device,
pcap_statustostr(status));
}
//激活句柄