tcp/quic lab finished

This commit is contained in:
2025-12-25 14:33:29 +08:00
parent ac5b4bc15d
commit 200566e8fe
261 changed files with 2664 additions and 0 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 406 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

View File

@ -0,0 +1,154 @@
#let times = "Times LT Pro"
#let times = "Times New Roman"
#let song = (times, "FZShuSong-Z01")
#let hei = (times, "FZHei-B01")
#let kai = (times, "FZKai-Z03")
#let xbsong = (times, "FZXiaoBiaoSong-B05")
#let fsong = (times, "FangSong_GB2312")
#let code = (times, "DejaVu Sans Mono")
#let nudtlabpaper(title: "",
author: "",
id: "",
training_type:"",
grade: "",
major: "",
department: "",
advisor: "",
jobtitle: "",
lab: "",
date: "",
header_str: "",
body) = {
// Set the document's basic properties.
set document(author: author, title: title)
set page(
margin: (left: 30mm, right: 30mm, top: 30mm, bottom: 30mm),
)
// Title row.
v(158pt)
align(center)[
#block(text(weight: 700, size: 30pt, font: hei, tracking: 15pt, "计算机网络"))
]
align(center)[
#block(text(weight: 700, size: 30pt, font: song, tracking: 15pt, "本科实验报告"))
]
v(103pt)
pad(
left: 1em,
right: 1em,
grid(
columns: (80pt, 1fr),
rows: (17pt, auto),
text(weight: 700, size: 16pt, font: song, "实验名称:"),
align(center, text(weight: "regular", size: 16pt, font: song, title)),
text(""),
line(length: 100%)
)
// #block(text(weight: 700, 1.75em, title))
// underline(text(weight: 700, size: 16pt, font: song, title))
)
// Author information.
v(82.5pt)
grid(
columns: (0.25fr, 0.25fr, 0.25fr, 0.25fr),
rows: (15pt, 8pt, 15pt, 8pt, 15pt, 8pt, 15pt, 8pt, 15pt),
text(size: 14pt, font: song, tracking: 10pt, "学员姓名"),
align(center, text(size: 14pt, font: song, author)),
text(size: 14pt, font: song, tracking: 54pt, "学号"),
align(center, text(size: 14pt, font: times, id)),
text(""),
line(length: 100%),
text(""),
line(length: 100%),
text(size: 14pt, font: song, tracking: 9pt, "培养类型"),
align(center, text(size: 14pt, font: song, training_type)),
text(size: 14pt, font: song, tracking: 54pt, "年级"),
align(center, text(size: 14pt, font: times, grade)),
text(""),
line(length: 100%),
text(""),
line(length: 100%),
text(size: 14pt, font: song, tracking: 54pt, "专业"),
align(center, text(size: 14pt, font: song, major)),
text(size: 14pt, font: song, tracking: 9pt, "所属学院"),
align(center, text(size: 14pt, font: song, department)),
text(""),
line(length: 100%),
text(""),
line(length: 100%),
text(size: 14pt, font: song, tracking: 9pt, "指导教员"),
align(center, text(size: 14pt, font: song, advisor)),
text(size: 14pt, font: song, tracking: 54pt, "职称"),
align(center, text(size: 14pt, font: song, jobtitle)),
text(""),
line(length: 100%),
text(""),
line(length: 100%),
text(size: 14pt, font: song, tracking: 20pt, "实验室"),
align(center, text(size: 14pt, font: song, lab)),
text(size: 14pt, font: song, tracking: 9pt, "实验时间"),
align(center, text(size: 14pt, font: song, date)),
text(""),
line(length: 100%),
text(""),
line(length: 100%),
)
v(50.5pt)
align(center, text(font: hei, size: 15pt, "国防科技大学教育训练部制"))
pagebreak()
set page(
margin: (left: 30mm, right: 30mm, top: 30mm, bottom: 30mm),
numbering: "i",
number-align: center,
)
v(14pt)
align(center)[
#block(text(font: hei, size: 14pt, "《本科实验报告》填写说明"))
]
v(14pt)
text("")
par(first-line-indent: 2em, text(font: song, size: 12pt, "实验报告内容编排应符合以下要求:"))
par(first-line-indent: 2em, text(font: fsong, size: 12pt, "1采用A421cm×29.7cm白色复印纸单面黑字。上下左右各侧的页边距均为3cm缺省文档网格字号为小4号中文为宋体英文和阿拉伯数字为Times New Roman每页30行每行36字页脚距边界为2.5cm页码置于页脚、居中采用小5号阿拉伯数字从1开始连续编排封面不编页码。"))
par(first-line-indent: 2em, text(font: fsong, size: 12pt, "2报告正文最多可设四级标题字体均为黑体第一级标题字号为4号其余各级标题为小4号标题序号第一级用“一、”、“二、”……第二级用“”、“” ……第三级用“1.”、“2.” ……第四级用“1”、“2” ……,分别按序连续编排。"))
par(first-line-indent: 2em, text(font: fsong, size: 12pt, "3正文插图、表格中的文字字号均为5号。"))
pagebreak()
set page(
margin: (left: 30mm, right: 30mm, top: 30mm, bottom: 30mm),
numbering: "1",
number-align: center,
)
set heading(numbering: "1.1")
// set text(font: hei, lang: "zh")
show heading: it => box(width: 100%)[
#v(0.50em)
#set text(font: hei)
#counter(heading).display()
// #h(0.5em)
#it.body
]
// Main body.
set par(justify: true)
body
}
#let para(t) = par(first-line-indent: 2em, text(font: song, size: 10.5pt, t))

BIN
network/arpicmplab/arp/main.pdf Executable file

Binary file not shown.

523
network/arpicmplab/arp/main.txt Executable file
View File

@ -0,0 +1,523 @@
#set page(header: [
#set par(spacing: 6pt)
#align(center)[#text(size: 11pt)[《计算机网络》实验报告]]
#v(-0.3em)
#line(length: 100%, stroke: (thickness: 1pt))
],)
#show heading: it => box(width: 100%)[
#v(0.50em)
#set text(font: hei)
#it.body
]
// #outline(title: "目录",depth: 3, indent: 1em)
// #outline(
// title: [图目录],
// target: figure.where(kind: image),
// )
#show heading: it => box(width: 100%)[
#v(0.50em)
#set text(font: hei)
#counter(heading).display()
// #h(0.5em)
#it.body
]
#set enum(indent: 0.5em,body-indent: 0.5em,)
#pagebreak()
// Display inline code in a small box
// that retains the correct baseline.
#show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
// Display block code in a larger block
// with more padding.
#show raw.where(block: true): it => block(
text(font: ("Consolas","FangSong_GB2312"), it),
fill: luma(240),
inset: 10pt,
radius: 4pt,
width: 100%,
)
= 实验目的与要求
== 实验目的
== 实验要求
= 实验内容
= 实验原理
= 实验环境
== 实验背景
== 实验设备
#para[
#align(center)[#table(
columns: (auto, auto,auto),
rows:(2em,2em,3em),
inset: 10pt,
align: horizon+center,
table.header(
[*设备名称*], [*设备型号*], [*设备数量*]
),
"交换机", "华为S5735", "2",
"PC", "联想启天M410
Windows 10", "4",
)]
另有网线若干控制线2条。
]
= 实验步骤
== 环境配置
=== 虚拟机网络配置
#para[
安装Windows 10虚拟机并配置物理机和虚拟机的IP地址使其能够互相访问
- 物理机网卡IP地址配置为`192.168.254.1/24`
- 虚拟机IP地址配置为`192.168.254.3/24`。
#figure(image("物理机虚拟机IP配置.png",format: "png",width: 90%,fit: "stretch"),caption: "物理机与虚拟机IP配置")
配置好之后,在两边的命令行中分别使用`ping`命令测试是否能够互相访问。同时在物理机上开启Wireshark以过滤条件`icmp`进行抓包查看IP地址是否正确
#figure(image("环境配置ping测试.png",format: "png",width: 100%,fit: "stretch"),caption: "环境配置ping通测试")<figure2>
从@figure2 中可以看到物理机和虚拟机之间可以互相访问且Wireshark抓包显示IP地址正确。
]
=== 使用CMake运行项目
#para[
CMake配置较为简单。首先在开发工具中安装对应版本CMake插件。其次在终端中进入项目根目录在此使用```shell mkdir build```命令新建`build`文件夹并进入该文件夹。接下来使用CMake工具生成对应的Makefile文件```shell cmake -G"MinGW Makefiles" ..```。
然后再运行```shell make```命令编译项目,最后使用```shell xnet.exe```命令即可运行项目:
#figure(image("cmake编译运行.png",format: "png",width: 70%,fit: "stretch"),caption: "CMake配置")
其中MinGW是一个Windows下的GNU编译器套件可以在Windows下编译出Linux下的可执行文件。```shell cmake -G"MinGW Makefiles" ..```命令的作用是配置使用MinGW编译器。
至此,环境配置结束。
]
== 实现ARP协议
#para[
代码已经实现了最基础的以太网协议实现了以太网帧的封装和解封装。接下来在此基础上继续实现ARP协议。
]
=== 定义相关数据结构
#para[
在`xnet_tiny.h`中定义IP地址长度以及数据结构
```c
#define XNET_IPV4_ADDR_SIZE 4 // IP地址长度
// IP地址
typedef union _xipaddr_t {
uint8_t array[XNET_IPV4_ADDR_SIZE]; // 以数据形式存储的ip
uint32_t addr; // 32位的ip地址
}xipaddr_t;
```
该数据结构定义了IP地址的数据结构包括了IP地址的数组形式和32位的IP地址。
然后定义MAC地址的长度以及ARP表项的结构体
```c
#define XNET_MAC_ADDR_SIZE 6 // MAC地址长度
// ARP表项
typedef struct _xarp_entry_t {
xipaddr_t ipaddr; // ip地址
uint8_t macaddr[XNET_MAC_ADDR_SIZE]; // mac地址
uint8_t state; // 状态位
uint16_t tmo; // 当前超时
uint8_t retry_cnt; // 当前重试次数
}xarp_entry_t;
```
该结构体定义了ARP表项的数据结构包括了IP地址、MAC地址、状态位、超时时间和重试次数。
定义ARP表项的最大数量
```c
#define XARP_CFG_ENTRY_SIZE 6 // ARP表大小
```
随后,在`xnet_tiny.c`中将ARP表定义为全局变量并定义一个表项指针方便后续代码编写
```c
static xarp_entry_t arp_table[XARP_CFG_ENTRY_SIZE]; // ARP表
static xarp_entry_t* arp_entry; // ARP表项指针
```
]
=== ARP表初始化
#para[
接下来编写ARP表的初始化函数。首先在`xnet_tiny.h`中定义ARP表项的第一个状态
```c
#define XARP_ENTRY_FREE 0 // ARP表项空闲
```
然后在`xnet_tiny.c`中定义初始化函数```c void xarp_init(void)```
```c
// ARP初始化
void xarp_init(void) {
for (arp_entry = arp_table;
arp_entry < XARP_CFG_ENTRY_SIZE * sizeof(xarp_entry_t) + arp_table;
arp_entry = arp_entry + sizeof(xarp_entry_t))
{
arp_entry->state = XARP_ENTRY_FREE; // 此处用到了上面定义的状态
}
arp_entry = arp_table;
}
```
初始化函数```c void xarp_init(void)```是一个循环。首先将前面定义的全局表项指针指向ARP表的第一个表项循环结束条件为指针指向的表项的地址超过ARP表的最后一个表项的地址。循环会遍历ARP表中的所有表项将表项状态初始化为`XARP_STATE_FREE`。最后,函数会将表项指针指向第一个表项,避免其他初始化过程中可能的指针越界问题。
最后,在协议栈的初始化函数中添加```c xarp_init()```
```c
void xnet_init (void) {
ethernet_init(); // 初始化以太网
xarp_init(); // *初始化ARP
}
```
]
=== 定义ARP报文
#para[
接下来编写无回报ARP报文的相关函数所以需要先定义ARP报文结构以及它所用到的相关结构。
首先在`xnet_tiny.h`中定义ARP报文中的几个字段。可以靠Wireshark抓包分析来获取这些字段的值下面是一个示例展示通过抓包来获取```c XNET_PROTOCOL_IP = 0x0800```
#figure(table(
columns: (auto),
rows:(auto,auto),
inset: 10pt,
align: horizon+center,
figure(image("抓一个arp分析结构.png",format: "png",fit:"stretch",width: 100%),),
figure(image("分析结构2.png",format: "png",fit:"stretch",width: 100%),),
stroke: none,
),caption: "通过抓包分析来获取字段值",kind: image)
代码编写如下:
```c
#define XARP_HW_ETHER 0x1 // 硬件类型:以太网
#define XARP_REQUEST 0x1 // OpcodeARP请求包
#define XARP_REPLY 0x2 // OpcodeARP响应包
typedef enum _xnet_protocol_t {
XNET_PROTOCOL_ARP = 0x0806, // ARP协议
XNET_PROTOCOL_IP = 0x0800, // IPv4协议
XNET_PROTOCOL_ICMP = 1, // ICMP协议
}xnet_protocol_t;
```
然后定义ARP报文的数据结构
```c
typedef struct _xarp_packet_t {
uint16_t hw_type, pro_type; // 硬件类型和协议类型
uint8_t hw_len, pro_len; // 硬件地址长 + 协议地址长
uint16_t opcode; // 请求/响应
uint8_t sender_mac[XNET_MAC_ADDR_SIZE]; // 发送包硬件地址
uint8_t sender_ip[XNET_IPV4_ADDR_SIZE]; // 发送包协议地址
uint8_t target_mac[XNET_MAC_ADDR_SIZE]; // 接收方硬件地址
uint8_t target_ip[XNET_IPV4_ADDR_SIZE]; // 接收方协议地址
}xarp_packet_t;
```
然后,使用前面定义的```c union xipaddr_t```结构,在`xnet_tiny.h`和`xnet_tiny.c`中定义ARP报文发送函数需要用到的IP地址、组播MAC地址
```c
// xnet_tiny.h
#define XNET_CFG_NETIF_IP {192, 168, 254, 2} // 本项目模拟出的网卡的IP
// xnet_tiny.c
static const xipaddr_t netif_ipaddr = XNET_CFG_NETIF_IP;
static const uint8_t ether_broadcast[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
```
至此定义ARP报文的数据结构结束。
]
=== ARP报文发送函数
#para[
下面编写ARP报文发送函数```c xarp_make_request(const xipaddr_t * ipaddr)```。
```c
/**
* 产生一个ARP请求请求网络指定ip地址的机器发回一个ARP响应
* @param ipaddr 请求的IP地址
* @return 请求结果
*/
xnet_err_t xarp_make_request(const xipaddr_t * ipaddr) {
xarp_packet_t* arp_packet;
xnet_packet_t * packet = xnet_alloc_for_send(sizeof(xarp_packet_t));
arp_packet = (xarp_packet_t *)packet->data;
arp_packet->hw_type = swap_order16(XARP_HW_ETHER); // 设置硬件类型为以太网
arp_packet->pro_type = swap_order16(XNET_PROTOCOL_IP); // 设置协议类型为IP
arp_packet->hw_len = XNET_MAC_ADDR_SIZE; // 设置硬件地址长度
arp_packet->pro_len = XNET_IPV4_ADDR_SIZE; // 设置协议地址长度
arp_packet->opcode = swap_order16(XARP_REQUEST); // 设置操作码为ARP请求
// 复制发送方MAC地址
memcpy(arp_packet->sender_mac, netif_mac, XNET_MAC_ADDR_SIZE);
// 复制发送方IP地址
memcpy(arp_packet->sender_ip, netif_ipaddr.array, XNET_IPV4_ADDR_SIZE);
// 目标MAC地址清零
memset(arp_packet->target_mac, 0, XNET_MAC_ADDR_SIZE);
// 复制目标IP地址
memcpy(arp_packet->target_ip, ipaddr->array, XNET_IPV4_ADDR_SIZE);
// 通过以太网发送ARP请求
return ethernet_out_to(XNET_PROTOCOL_ARP, ether_broadcast, packet);
}
```
这个函数的主要功能是生成并发送一个ARP请求报文以请求指定IP地址即函数的输入```c const xipaddr_t * ipaddr```的机器返回其MAC地址。函数的具体步骤如下
1. 分配一个用于发送的ARP数据包```c arp_packet```并将其数据段设置为ARP报文结构。
2. 设置ARP报文的各个字段包括硬件类型`hw_type`、协议类型`pro_type`、硬件地址长度`hw_len`、协议地址长度`pro_len`、操作码`opcode`(设置为`XARP_REQUEST`)等。
3. 复制发送方即本项目模拟出的网卡的MAC地址和IP地址到ARP报文中。
4. 将目标MAC地址字段清零并复制目标IP地址到ARP报文中。
5. 最后通过以太网发送该ARP请求报文返回发送结果状态码
]
=== 启动时的ARP请求
#para[
在以太网协议的初始化函数```c static xnet_err_t ethernet_init(void)```中添加一个ARP请求
```c
/**
* 以太网初始化
* @return 初始化结果
*/
static xnet_err_t ethernet_init (void) {
xnet_err_t err = xnet_driver_open(netif_mac);
if (err < 0) return err;
return xarp_make_request(&netif_ipaddr); // 发送ARP请求
}
```
这样当协议栈初始化时会发送一个ARP请求。
下面用Wireshark抓包来验证ARP请求是否发送成功。首先重新编译项目其次开启Wireshark抓包最后启动程序
#figure(image("启动ARP2.png",format: "png",width: 100%,fit: "stretch"),caption: "启动时的ARP请求")<figure3>
从@figure3 中可以看到ARP请求发送成功说明编写至此的代码没有问题。
]
=== ARP报文接收函数
#para[
ARP报文接收函数主要功能是处理接收到的ARP报文包括解析报文、更新ARP表、发送ARP响应等。下面根据这些需求编写ARP报文接收函数```c void xarp_in(xnet_packet_t * packet)```
```c
/**
* 处理接收到的ARP包
* @param packet 输入的ARP包
*/
void xarp_in(xnet_packet_t * packet) {
// 检查包的大小是否符合ARP包的最小长度要求
if (packet->size >= sizeof(xarp_packet_t)) {
xarp_packet_t * arp_packet = (xarp_packet_t *) packet->data;
uint16_t opcode = swap_order16(arp_packet->opcode);
// 检查包的合法性,包括硬件类型、硬件地址长度、协议类型、协议地址长度和操作码
if ((swap_order16(arp_packet->hw_type) != XARP_HW_ETHER) ||
(arp_packet->hw_len != XNET_MAC_ADDR_SIZE) ||
(swap_order16(arp_packet->pro_type) != XNET_PROTOCOL_IP) ||
(arp_packet->pro_len != XNET_IPV4_ADDR_SIZE)
|| ((opcode != XARP_REQUEST) && (opcode != XARP_REPLY))) {
return;
}
// 只处理目标IP地址为自己的ARP请求或响应包
if (!xipaddr_is_equal_buf(&netif_ipaddr, arp_packet->target_ip)) {
return;
}
// 根据操作码进行处理
switch (swap_order16(arp_packet->opcode)) {
case XARP_REQUEST: // 处理ARP请求发送ARP响应并更新ARP表项
xarp_make_response(arp_packet);
update_arp_entry(arp_packet->sender_ip, arp_packet->sender_mac);
break;
case XARP_REPLY: // 处理ARP响应更新ARP表项
update_arp_entry(arp_packet->sender_ip, arp_packet->sender_mac);
break;
}
}
}
```
该函数主要功能是处理接收到的ARP包。首先进行简单的长度判断避免后续字段读取失败造成内存错误。随后检查包的合法性包括硬件类型、硬件地址长度、协议类型、协议地址长度和操作码。APR响应只要求机器处理目标IP地址为自己的ARP请求或响应包所以使用```c if (!xipaddr_is_equal_buf(&netif_ipaddr, arp_packet->target_ip))```来判断。最后根据操作码进行处理分别处理ARP请求和ARP响应
- ARP请求发送ARP响应```c xarp_make_response(...)```并更新ARP表项```c update_arp_entry(...)```
- ARP响应只需要更新ARP表项。
其中,用到的宏```c xipaddr_is_equal_buf()```函数用于比较两个IP地址是否相等实现如下
```c
// 比较IP地址是否相等
#define xipaddr_is_equal_buf(addr, buf) (memcmp(
(addr)->array,
(buf),
XNET_IPV4_ADDR_SIZE
)
== 0
)
```
然后,需要编写上面函数中调用的两个函数:```c xarp_make_response()```和```c update_arp_entry()```。
```c xarp_make_response()```函数主要功能是输入一个ARP请求包通过此包内的源信息生成对应的ARP响应并发送出去。具体代码如下
```c
/**
* 生成一个ARP响应
* @param arp_packet 接收到的ARP请求包
* @return 生成结果
*/
xnet_err_t xarp_make_response(xarp_packet_t * arp_packet) {
xarp_packet_t* response_packet;
xnet_packet_t * packet = xnet_alloc_for_send(sizeof(xarp_packet_t));
response_packet = (xarp_packet_t *)packet->data;
response_packet->hw_type = swap_order16(XARP_HW_ETHER); // 设置硬件类型为以太网
response_packet->pro_type = swap_order16(XNET_PROTOCOL_IP); // 设置协议类型为IP
response_packet->hw_len = XNET_MAC_ADDR_SIZE; // 设置硬件地址长度
response_packet->pro_len = XNET_IPV4_ADDR_SIZE; // 设置协议地址长度
response_packet->opcode = swap_order16(XARP_REPLY); // 设置操作码为ARP响应
// 复制目标MAC地址
memcpy(response_packet->target_mac, arp_packet->sender_mac, XNET_MAC_ADDR_SIZE);
// 复制目标IP地址
memcpy(response_packet->target_ip, arp_packet->sender_ip, XNET_IPV4_ADDR_SIZE);
// 复制发送方MAC地址
memcpy(response_packet->sender_mac, netif_mac, XNET_MAC_ADDR_SIZE);
// 复制发送方IP地址
memcpy(response_packet->sender_ip, netif_ipaddr.array, XNET_IPV4_ADDR_SIZE);
// 通过以太网发送ARP响应
return ethernet_out_to(XNET_PROTOCOL_ARP, ether_broadcast, packet);
}
```
可以发现此函数与前面的ARP请求函数```c xarp_make_request()```非常相似,只是操作码不同,此处为`XARP_REPLY`其他字段均从源ARP请求报文中获取并填入对应区域。
```c update_arp_entry()```函数主要功能是更新所有ARP表项附带一定的可视化功能。具体代码如下
```c
/**
* 更新ARP表项
* @param src_ip 源IP地址
* @param mac_addr 对应的mac地址
*/
static void update_arp_entry(uint8_t* src_ip, uint8_t* mac_addr) {
for (arp_entry = arp_table;
arp_entry < XARP_CFG_ENTRY_SIZE * sizeof(xarp_entry_t) + arp_table;
arp_entry = arp_entry + sizeof(xarp_entry_t))
{
// 检查ARP表项是否为空或者是否与给定的源IP地址匹配且状态不是有效的
if (arp_entry->state == XARP_ENTRY_FREE ||
( arp_entry->state == XARP_ENTRY_OK
&& xipaddr_is_equal_buf(&arp_entry->ipaddr, src_ip)
))
{
// 更新ARP表项中的IP地址和MAC地址
memcpy(arp_entry->ipaddr.array, src_ip, XNET_IPV4_ADDR_SIZE);
memcpy(arp_entry->macaddr, mac_addr, 6);
printf("learned☝🤓mac addr\n");
for (
int i = 0;
i < sizeof(mac_addr) / sizeof(mac_addr[0]);
++i)
{
printf("%02X%c",
mac_addr[i],
i < sizeof(mac_addr) / sizeof(mac_addr[0]) - 1 ? ':' : '\n'
);
}
// 设置ARP表项状态为有效
arp_entry->state = XARP_ENTRY_OK;
// 设置ARP表项的超时时间
arp_entry->tmo = XARP_CFG_ENTRY_OK_TMO;
// 设置ARP表项的重试次数
arp_entry->retry_cnt = XARP_CFG_MAX_RETRIES;
print_arp_table(); // 打印完整的ARP表
return; // 更新后退出函数
}
}
// 如果ARP表已满采用LRU策略替换最老的表项
arp_entry = arp_table; // 重置arp_entry指向表头
xarp_entry_t* oldest_entry = NULL;
uint32_t oldest_tmo = 0xFFFFFFFF;
for (arp_entry = arp_table;
arp_entry < XARP_CFG_ENTRY_SIZE * sizeof(xarp_entry_t) + arp_table;
arp_entry = arp_entry + sizeof(xarp_entry_t))
{
if (arp_entry->tmo < oldest_tmo) {
oldest_tmo = arp_entry->tmo;
oldest_entry = arp_entry;
}
}
if (oldest_entry != NULL) {
// 更新最老的ARP表项
memcpy(oldest_entry->ipaddr.array, src_ip, XNET_IPV4_ADDR_SIZE);
memcpy(oldest_entry->macaddr, mac_addr, 6);
printf("learned☝🤓mac addr\n");
for (int i = 0; i < sizeof(mac_addr) / sizeof(mac_addr[0]); ++i) {
printf("%02X%c", mac_addr[i], i < sizeof(mac_addr) / sizeof(mac_addr[0]) - 1 ? ':' : '\n');
}
// 设置ARP表项状态为有效
oldest_entry->state = XARP_ENTRY_OK;
// 设置ARP表项的超时时间
oldest_entry->tmo = XARP_CFG_ENTRY_OK_TMO;
// 设置ARP表项的重试次数
oldest_entry->retry_cnt = XARP_CFG_MAX_RETRIES;
print_arp_table(); // 打印完整的ARP表
}
}
```
这个函数很长。它主要功能是更新ARP表项。更新分为两种情况
- ARP表还有空闲表项
- ARP表已满采用LRU策略替换最老的表项
首先函数通过遍历ARP表中的所有表项检查表项是否为空或者是否与给定的源IP地址匹配且状态不是有效的。如果满足条件则更新ARP表项中的IP地址和MAC地址并设置表项状态为有效设置超时时间和重试次数最后会打印完整的ARP表。如果ARP表已满则采用LRU策略替换最老的表项。函数会遍历ARP表找到超时时间最小的表项并更新该表项的IP地址和MAC地址设置表项状态为有效设置超时时间和重试次数最后打印完整的ARP表。
用到的打印函数实现如下:
```c
/**
* 打印完整的ARP表
*/
void print_arp_table() {
printf("\n----ARP Table----\n");
for (arp_entry = arp_table; arp_entry < XARP_CFG_ENTRY_SIZE * sizeof(xarp_entry_t) + arp_table; arp_entry = arp_entry + sizeof(xarp_entry_t)) {
if (arp_entry->state != XARP_ENTRY_FREE) {
printf("IP: ");
for (int i = 0; i < XNET_IPV4_ADDR_SIZE; ++i) {
printf("%d%c",
arp_entry->ipaddr.array[i],
i < XNET_IPV4_ADDR_SIZE - 1 ? '.' : '\n'
);
}
printf("MAC: ");
for (int i = 0; i < 6; ++i) {
printf("%02X%c", arp_entry->macaddr[i], i < 5 ? ':' : '\n');
}
printf(
"State: %s\n",
arp_entry->state == XARP_ENTRY_FREE ? "FREE" :
arp_entry->state == XARP_ENTRY_RESOLVING ? "RESOLVING" : "OK"
);
}
}
printf("\n-----------------\n");
}
```
最后需要在以太网帧接收函数中添加ARP报文的处理
```c
/**
* 以太网数据帧输入输出
* @param packet 待处理的包
*/
static void ethernet_in (xnet_packet_t * packet) {
// 至少要比头部数据大
if (packet->size <= sizeof(xether_hdr_t)) {
return;
}
// 根据协议类型分发到不同的处理函数
xether_hdr_t* hdr = (xether_hdr_t*)packet->data;
switch (swap_order16(hdr->protocol)) {
case XNET_PROTOCOL_ARP:
// 移除以太网头部处理ARP协议
remove_header(packet, sizeof(xether_hdr_t));
xarp_in(packet);
break;
case XNET_PROTOCOL_IP: {
break;
}
}
}
```
其中,主要在```c case XNET_PROTOCOL_ARP```中添加了对ARP报文的处理。
在继续之前再次使用Wireshark检验这部分代码编写。重新编译后按照以下流程进行检验
- 开启Wireshark抓包
- 运行本程序;
- 在虚拟机上ping本程序以触发ARP请求
- 查看Wireshark抓包结果和程序输出。
#figure(image("ARP响应.png",format: "png",width: 100%,fit: "stretch"),caption: "ARP请求响应")<figure4>
从@figure4 中可以看到ARP响应都发送成功程序输出中也表明学习到了虚拟机的MAC地址说明代码编写正确。
]
=== ARP超时重传
= 实验总结
== 内容总结
== 心得感悟
#show heading: it => box(width: 100%)[
#v(0.50em)
#set text(font: hei)
// #counter(heading).display()
// #h(0.5em)
#it.body
]
#pagebreak()
#bibliography("ref.yml",full: true,title: "参考文献",style:"gb-7714-2015-numeric")

964
network/arpicmplab/arp/main.typ Executable file
View File

@ -0,0 +1,964 @@
#import "labtemplate.typ": *
#show: nudtlabpaper.with(title: "TCP/IP 协议栈 ARP 协议实现实验",
author: "王李烜",
id: "202202001046",
training_type: "无军籍",
grade: "2022",
major: "网络工程",
department: "计算机学院",
advisor: "邱振宇",
jobtitle: "讲师",
lab: "305-505",
date: "2024.12.16",
header_str: "《计算机网络》实验报告",
)
#set page(header: [
#set par(spacing: 6pt)
#align(center)[#text(size: 11pt)[《计算机网络》实验报告]]
#v(-0.3em)
#line(length: 100%, stroke: (thickness: 1pt))
],)
#show heading: it => box(width: 100%)[
#v(0.50em)
#set text(font: hei)
#it.body
]
#outline(title: "目录",depth: 3, indent: 1em)
#pagebreak()
#outline(
title: [图目录],
target: figure.where(kind: image),
)
#show heading: it => box(width: 100%)[
#v(0.50em)
#set text(font: hei)
#counter(heading).display()
// #h(0.5em)
#it.body
]
#set enum(indent: 0.5em,body-indent: 0.5em,)
#pagebreak()
= 实验概要
== 实验内容
#para[
本次实验的主要内容 ARP 协议实现。本次实验包含基础任务和拓展任务两部分,
具体任务要求如下:
- 基础任务:编写程序,完善 TCP/IP 协议栈的 ARP 协议部分。围绕 ARP 的初始化、无回报 ARP 的生成、ARP 的输入处理,以及 ARP 的超时重新请 求几个部分完成。并且保证完成 ARP 协议的完整实现。#box(
text(font: ("Times LT Pro","FZXiaoBiaoSong-B05"),fill: luma(240), weight:"bold", "本实验中Completed!"),
fill:blue,
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,)
- 拓展任务:拓展任务是可选任务,在基础任务实现的 ARP 协议实现基础上, 可选择性的完成如下任务:
+ ARP 多个表项的实现;#box(
text(font: ("Times LT Pro","FZXiaoBiaoSong-B05"),fill: luma(240), weight:"bold", "本实验中Completed!"),
fill:blue,
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,)
+ IP 层的输入输出处理。#box(
text(font: ("Times LT Pro","FZXiaoBiaoSong-B05"),fill: luma(240), weight:"bold", "本实验中Completed!"),
fill:blue,
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,)
]
== 实验要求
#para[
本实验的具体过程及对应要求如下:
- 实验开始前准备工作:在实验开始前,学员需要掌握 C语言 编程基础,理解 TCP/IP 协议栈的工作原理,尤其是 ARP 协议的功能和作用。同时,熟悉 MAC 地址与 IP 地址的转换原理,了解网络设备如何通过 ARP 请求与响应进行地址解析。
- 实验过程中:按照实验要求,完成 ARP 协议的实现。具体步骤包括:具体而言,构造 ARP 请求和响应报文,实现报文格式的编码与解析。发送 ARP请求构建并广播 ARP 请求,获取目标设备的 MAC 地址。处理 ARP 响应,在收到响应后,提取并记录目标 IP MAC 地址的映射。管理 ARP 缓存,设计缓存机制,存储 IP-MAC 映射,并实现超时处理机制。
- 实验结束后:总结 ARP 协议的实现过程,详细描述报文格式、缓存管理和通信流程,并根据实验要求撰写实验报告,分析实验结果。
]
== 实验目的
#para[
在现代网络环境中, ARP协议广泛应用于各种网络设备和系统如计算机、路由器和交换机等。深入理解ARP的工作原理有助于掌握网络设备之间的通信机制理解数据在网络中的传输过程。特别是对于网络工程和网络安全领域从协议层面了解ARP有助于识别和防范诸如ARP欺骗等网络攻击提高网络的安全防护能力。
通过本次实验学员将亲自动手实现ARP协议的核心功能包括ARP请求与响应的构建与解析、ARP缓存表的管理等。这不仅加深了对TCP/IP协议栈的理解也培养了实际编程和问题解决的能力。掌握ARP协议的实现对后续学习更复杂的网络协议如IP、ICMP、TCP和UDP以及从事网络相关工作都有重要的意义。
]
// Display inline code in a small box
// that retains the correct baseline.
#show raw.where(block: false): it => box(
text(font: ("Consolas","FangSong_GB2312"), it),
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
// Display block code in a larger block
// with more padding.
#show raw.where(block: true): it => block(
text(font: ("Consolas","FangSong_GB2312"), it),
fill: luma(240),
inset: 10pt,
radius: 4pt,
width: 100%,
)
= 实验原理及方案
#para[
ARP地址解析协议 TCP/IP 协议族中用于将 IP 地址解析为 MAC 地址的重要协议。IP 通信依赖于数据链路层的硬件地址MAC 地址),而 ARP 负责动态地将网络层的 IP 地址转换为对应的数据链路层 MAC 地址从而实现设备间的通信。ARP 协议的实现主要包括发送 ARP 请求、接收并处理 ARP 响应、更新 ARP 缓存、以及缓存超时机制。
]
== ARP的初始化
#para[
在一个典型的局域网中,设备通过 IP 地址进行网络层通信,但 IP 地址并不能直接用于数据链路层传输。以太网等数据链路层协议使用 MAC 地址进行通信,因此,发送设备需要将目标 IP 地址解析为 MAC 地址才能发送数据帧。
如果该设备的 ARP 缓存中没有目标设备的 MAC 地址映射,它会广播 ARP 请求,询问网络上哪个设备持有特定的 IP 地址。ARP 请求是一个以太网层的广播包,发送到子网内所有设备,只有持有目标 IP 地址的设备才会进行响应。
ARP 初始化的过程是设备发现并解析网络中其他设备的关键步骤。ARP 请求包含源设备的 IP 地址和 MAC 地址,而目标设备通过 ARP 响应提供其对应的 MAC 地址。这个机制确保设备能够通过网络层IP 地址和链路层MAC 地址)之间建立正确的映射关系。
]
== 无回报 ARP 的生成
#para[
无回报 ARPGratuitous ARP又称为“主动 ARP”或“自愿 ARP”是一种特殊的 ARP 操作。与典型的 ARP 请求不同,无回报 ARP 并不是为了解析目标设备的 MAC 地址,而是设备主动向网络发送广播 ARP 包,通常用于更新网络中的 IP-MAC 映射关系、检测 IP 地址冲突等。
无回报 ARP 是设备主动广播自身的 IP 地址和 MAC 地址,不带有显式的 ARP 请求和响应互动。其主要目的是通知网络中其他设备更新其 ARP 缓存表中的信息。这种情况下,设备并不期待其他设备回应。它是单向广播的,通常被用于下列几种情况:
- 更新网络中的 ARP 表:当设备的 MAC 地址或 IP 地址发生变动时,可以主动发送无回报 ARP以便通知网络中其他设备更新其 ARP 缓存。
- IP 冲突检测:设备在启动时,通过发送无回报 ARP 来检测是否有其他设备占用了相同的 IP 地址。如果另一台设备使用了相同的 IP 地址,它会回应此 ARP 广播,从而帮助设备检测到 IP 冲突。
- 负载均衡器和高可用性系统:当系统切换主备设备时,备设备通常会发送无回报 ARP 来通知网络中的所有节点其 IP-MAC 映射已经改变,避免继续向已下线的设备发送数据。
无回报 ARP 的生成过程如下:
1. 生成 ARP 广播包:设备在确定需要广播自身 IP-MAC 映射时,会生成一个 ARP 广播包。该包包含设备自身的 IP 地址和 MAC 地址,并且目标硬件地址设置为全 0因为无回报 ARP 并不是请求对方设备的 MAC 地址,而是向网络中的所有设备广播自身的信息。
2. 设置操作码为 ARP 请求:尽管无回报 ARP 是主动广播,但它在帧结构中被标记为 ARP 请求(操作码为 1这使得网络中的其他设备会将其视为一种信息广播用于更新 ARP 缓存。
3. 发送广播ARP 广播包通过以太网层进行传输,目标 MAC 地址为 FF:FF:FF:FF:FF:FF即局域网内的所有设备都可以接收到此广播。
4. 网络中的设备处理:网络中所有收到此广播的设备会检查 ARP 包中的发送方 IP 地址和 MAC 地址,并将其更新到本地的 ARP 缓存表中。这样,即使该 IP 地址之前未出现在这些设备的 ARP 表中,它们也会记录并更新新的映射。
]
== ARP 的输入处理
#para[
ARP地址解析协议的输入处理指的是设备在接收到 ARP 请求或响应时,如何对该 ARP 报文进行解析和处理,并据此更新设备的 ARP 缓存或进一步采取必要的网络行为。ARP 输入处理的核心任务是解析报文,更新 ARP 缓存,并根据报文类型采取不同的操作。
在这部分有以下步骤:
- 接收 ARP 报文:设备通过网络接口接收到 ARP 报文,无论是广播还是单播形式。这些 ARP 报文可以是 ARP 请求、ARP 响应,或者是无回报 ARP。
- 解析 ARP 报文:设备对 ARP 报文进行解析,提取其中的关键信息。
- 检查报文有效性:设备检查 ARP 报文的有效性,包括检查硬件类型是否为以太网、协议类型是否为 IPv4、操作码是否为合法的请求或响应。如果报文不符合 ARP 协议规定,设备将丢弃该报文。
- 更新 ARP 缓存:根据 ARP 报文中的信息,设备更新自己的 ARP 缓存表。设备通常会把报文中的发送方 IP 地址和发送方 MAC 地址映射记录下来,以便将来进行快速的 IP MAC 地址解析。
- 据操作码进行处理:不同类型的 ARP 报文有不同的处理方式:
- 如果接收到的是 ARP 请求,设备需要检查目标 IP 地址是否与自身的 IP 地址匹配,如果匹配,则需要发送一个 ARP 响应包,告知请求设备自己的 MAC 地址。
- 如果接收到的是 ARP 响应,设备会根据响应包中的信息,更新或添加到 ARP 缓存表,并不再发送进一步的响应。
- 如果接收到的是无回报 ARP设备会将报文中的 IP-MAC 映射记录下来,以更新其 ARP 缓存。
]
== ARP 的超时重新请求机制
#para[
ARP地址解析协议的超时重新请求机制指的是设备在尝试解析某个 IP 地址到 MAC 地址时,若未能在设定的时间内收到响应,会采取的重发 ARP 请求的策略。这种机制旨在保证网络设备在通信中能够及时获取目标设备的 MAC 地址,并维持 ARP 缓存的准确性。
ARP 缓存存储的是 IP 地址与 MAC 地址之间的映射关系。在通信过程中,网络设备通常会先查询 ARP 缓存以查找目标设备的 MAC 地址。如果缓存中存在该 IP 地址的记录,设备会直接使用缓存中的 MAC 地址进行通信;如果没有找到相应记录,设备会发出 ARP 请求,广播请求目标 IP 地址对应的 MAC 地址。
如果设备在发送 ARP 请求后,未能在指定的时间内收到 ARP 响应,它会认为该 ARP 请求失败。这时,设备会重新发送 ARP 请求,通常会进行一定次数的重发,以确保能够成功解析目标设备的 MAC 地址。
]
= 实验环境
== 实验设备与软件
#para[
#align(center)[#table(
columns: (auto, auto),
rows:(auto,auto,auto),
inset: 10pt,
align: horizon+center,
table.header(
[*名称*], [*型号或版本*],
),
"物理机", "联想ThinkPad-Windows 10 22H4",
"虚拟机", "Virtual Box-Windows 10 22H4",
"Wireshark", "Wireshark 4.4.0",
"CMake", "CMake 3.31.3"
)]
]
= 实验步骤
== 环境配置
=== 虚拟机网络配置
#para[
安装Windows 10虚拟机并配置物理机和虚拟机的IP地址使其能够互相访问
- 物理机网卡IP地址配置为`192.168.254.1/24`
- 虚拟机IP地址配置为`192.168.254.3/24`
#figure(image("物理机虚拟机IP配置.png",format: "png",width: 90%,fit: "stretch"),caption: "物理机与虚拟机IP配置")
配置好之后,在两边的命令行中分别使用`ping`命令测试是否能够互相访问。同时在物理机上开启Wireshark以过滤条件`icmp`进行抓包查看IP地址是否正确
#figure(image("环境配置ping测试.png",format: "png",width: 90%,fit: "stretch"),caption: "环境配置ping通测试")<figure2>
@figure2 中可以看到物理机和虚拟机之间可以互相访问且Wireshark抓包显示IP地址正确。
]
=== 使用CMake运行项目
#para[
CMake配置较为简单。首先在开发工具中安装对应版本CMake插件。其次在终端中进入项目根目录在此使用```shell mkdir build```命令新建`build`文件夹并进入该文件夹。接下来使用CMake工具生成对应的Makefile文件```shell cmake -G"MinGW Makefiles" ..```
然后再运行```shell make```命令编译项目,最后使用```shell xnet.exe```命令即可运行项目:
#figure(image("cmake编译运行.png",format: "png",width: 76%,fit: "stretch"),caption: "CMake配置")
其中MinGW是一个Windows下的GNU编译器套件可以在Windows下编译出Linux下的可执行文件。```shell cmake -G"MinGW Makefiles" ..```命令的作用是配置使用MinGW编译器。
至此,环境配置结束。
]
== 实现ARP协议
#para[
代码已经实现了最基础的以太网协议实现了以太网帧的封装和解封装。接下来在此基础上继续实现ARP协议。
]
=== 相关数据结构<multiple_entry>
#para[
`xnet_tiny.h`中定义IP地址长度以及数据结构
```c
#define XNET_IPV4_ADDR_SIZE 4 // IP地址长度
// IP地址
typedef union _xipaddr_t {
uint8_t array[XNET_IPV4_ADDR_SIZE]; // 以数据形式存储的ip
uint32_t addr; // 32位的ip地址
}xipaddr_t;
```
该数据结构定义了IP地址的数据结构包括了IP地址的数组形式和32位的IP地址。
然后定义MAC地址的长度以及ARP表项的结构体
```c
#define XNET_MAC_ADDR_SIZE 6 // MAC地址长度
// ARP表项
typedef struct _xarp_entry_t {
xipaddr_t ipaddr; // ip地址
uint8_t macaddr[XNET_MAC_ADDR_SIZE]; // mac地址
uint8_t state; // 状态位
uint16_t tmo; // 当前超时
uint8_t retry_cnt; // 当前重试次数
}xarp_entry_t;
```
该结构体定义了ARP表项的数据结构包括了IP地址、MAC地址、状态位、超时时间和重试次数。
定义ARP表项的最大数量
```c
#define XARP_CFG_ENTRY_SIZE 8 // ARP表大小
```
随后,在`xnet_tiny.c`将ARP表定义为全局变量并定义一个表项指针方便后续代码编写
```c
static xarp_entry_t arp_table[XARP_CFG_ENTRY_SIZE]; // ARP表
static xarp_entry_t* arp_entry; // ARP表项指针
```
]
=== ARP表初始化<State1>
#para[
接下来编写ARP表的初始化函数。首先在`xnet_tiny.h`中定义ARP表项的第一个状态
```c
#define XARP_ENTRY_FREE 0 // ARP表项空闲
```
然后在`xnet_tiny.c`中定义初始化函数```c void xarp_init(void)```
```c
// ARP初始化
void xarp_init(void) {
for (arp_entry = arp_table;
arp_entry < XARP_CFG_ENTRY_SIZE * sizeof(xarp_entry_t) + arp_table;
arp_entry = arp_entry + sizeof(xarp_entry_t))
{
arp_entry->state = XARP_ENTRY_FREE; // 此处用到了上面定义的状态
}
arp_entry = arp_table;
}
```
初始化函数```c void xarp_init(void)```是一个循环。首先将前面定义的全局表项指针指向ARP表的第一个表项循环结束条件为指针指向的表项的地址超过ARP表的最后一个表项的地址。循环会遍历ARP表中的所有表项将表项状态初始化为`XARP_STATE_FREE`。最后,函数会将表项指针指向第一个表项,避免其他初始化过程中可能的指针越界问题。
最后,在协议栈的初始化函数中添加```c xarp_init()```
```c
void xnet_init (void) {
ethernet_init(); // 初始化以太网
xarp_init(); // *初始化ARP
}
```
]
=== ARP报文
#para[
接下来编写无回报ARP报文的相关函数所以需要先定义ARP报文结构以及它所用到的相关结构。
首先在`xnet_tiny.h`中定义ARP报文中的几个字段。可以靠Wireshark抓包分析来获取这些字段的值下面是一个示例展示通过抓包来获取```c XNET_PROTOCOL_IP = 0x0800```
#figure(table(
columns: (auto),
rows:(auto,auto),
inset: 10pt,
align: horizon+center,
figure(image("抓一个arp分析结构.png",format: "png",fit:"stretch",width: 100%),),
figure(image("分析结构2.png",format: "png",fit:"stretch",width: 100%),),
stroke: none,
),caption: "通过抓包分析来获取字段值",kind: image)
代码编写如下:
```c
#define XARP_HW_ETHER 0x1 // 硬件类型:以太网
#define XARP_REQUEST 0x1 // OpcodeARP请求包
#define XARP_REPLY 0x2 // OpcodeARP响应包
typedef enum _xnet_protocol_t {
XNET_PROTOCOL_ARP = 0x0806, // ARP协议
XNET_PROTOCOL_IP = 0x0800, // IPv4协议
XNET_PROTOCOL_ICMP = 1, // ICMP协议
}xnet_protocol_t;
```
然后定义ARP报文的数据结构
```c
typedef struct _xarp_packet_t {
uint16_t hw_type, pro_type; // 硬件类型和协议类型
uint8_t hw_len, pro_len; // 硬件地址长 + 协议地址长
uint16_t opcode; // 请求/响应
uint8_t sender_mac[XNET_MAC_ADDR_SIZE]; // 发送包硬件地址
uint8_t sender_ip[XNET_IPV4_ADDR_SIZE]; // 发送包协议地址
uint8_t target_mac[XNET_MAC_ADDR_SIZE]; // 接收方硬件地址
uint8_t target_ip[XNET_IPV4_ADDR_SIZE]; // 接收方协议地址
}xarp_packet_t;
```
然后,使用前面定义的```c union xipaddr_t```结构,在`xnet_tiny.h``xnet_tiny.c`中定义ARP报文发送函数需要用到的IP地址、组播MAC地址
```c
// xnet_tiny.h
#define XNET_CFG_NETIF_IP {192, 168, 254, 2} // 本项目模拟出的网卡的IP
// xnet_tiny.c
static const xipaddr_t netif_ipaddr = XNET_CFG_NETIF_IP;
static const uint8_t ether_broadcast[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
```
至此定义ARP报文的数据结构结束。
]
=== ARP报文发送函数
#para[
下面编写ARP报文发送函数```c xarp_make_request(const xipaddr_t * ipaddr)```
```c
/**
* 产生一个ARP请求请求网络指定ip地址的机器发回一个ARP响应
* @param ipaddr 请求的IP地址
* @return 请求结果
*/
xnet_err_t xarp_make_request(const xipaddr_t * ipaddr) {
xarp_packet_t* arp_packet;
xnet_packet_t * packet = xnet_alloc_for_send(sizeof(xarp_packet_t));
arp_packet = (xarp_packet_t *)packet->data;
arp_packet->hw_type = swap_order16(XARP_HW_ETHER); // 设置硬件类型为以太网
arp_packet->pro_type = swap_order16(XNET_PROTOCOL_IP); // 设置协议类型为IP
arp_packet->hw_len = XNET_MAC_ADDR_SIZE; // 设置硬件地址长度
arp_packet->pro_len = XNET_IPV4_ADDR_SIZE; // 设置协议地址长度
arp_packet->opcode = swap_order16(XARP_REQUEST); // 设置操作码为ARP请求
// 复制发送方MAC地址
memcpy(arp_packet->sender_mac, netif_mac, XNET_MAC_ADDR_SIZE);
// 复制发送方IP地址
memcpy(arp_packet->sender_ip, netif_ipaddr.array, XNET_IPV4_ADDR_SIZE);
// 目标MAC地址清零
memset(arp_packet->target_mac, 0, XNET_MAC_ADDR_SIZE);
// 复制目标IP地址
memcpy(arp_packet->target_ip, ipaddr->array, XNET_IPV4_ADDR_SIZE);
// 通过以太网发送ARP请求
return ethernet_out_to(XNET_PROTOCOL_ARP, ether_broadcast, packet);
}
```
这个函数的主要功能是生成并发送一个ARP请求报文以请求指定IP地址即函数的输入```c const xipaddr_t * ipaddr```的机器返回其MAC地址。函数的具体步骤如下
1. 分配一个用于发送的ARP数据包```c arp_packet```并将其数据段设置为ARP报文结构。
2. 设置ARP报文的各个字段包括硬件类型`hw_type`、协议类型`pro_type`、硬件地址长度`hw_len`、协议地址长度`pro_len`、操作码`opcode`(设置为`XARP_REQUEST`)等。
3. 复制发送方即本项目模拟出的网卡的MAC地址和IP地址到ARP报文中。
4. 将目标MAC地址字段清零并复制目标IP地址到ARP报文中。
5. 最后通过以太网发送该ARP请求报文返回发送结果状态码
]
=== 启动时的ARP请求
#para[
在以太网协议的初始化函数```c static xnet_err_t ethernet_init(void)```中添加一个ARP请求
```c
/**
* 以太网初始化
* @return 初始化结果
*/
static xnet_err_t ethernet_init (void) {
xnet_err_t err = xnet_driver_open(netif_mac);
if (err < 0) return err;
return xarp_make_request(&netif_ipaddr); // 发送ARP请求
}
```
这样当协议栈初始化时会发送一个ARP请求。
下面用Wireshark抓包来验证ARP请求是否发送成功。首先重新编译项目其次开启Wireshark抓包最后启动程序
#figure(image("启动ARP2.png",format: "png",width: 100%,fit: "stretch"),caption: "启动时的ARP请求")<figure3>
@figure3 中可以看到ARP请求发送成功说明编写至此的代码没有问题。
]
=== ARP报文接收函数
#para[
ARP报文接收函数主要功能是处理接收到的ARP报文包括解析报文、更新ARP表、发送ARP响应等。下面根据这些需求编写ARP报文接收函数```c void xarp_in(xnet_packet_t * packet)```
```c
/**
* 处理接收到的ARP包
* @param packet 输入的ARP包
*/
void xarp_in(xnet_packet_t * packet) {
// 检查包的大小是否符合ARP包的最小长度要求
if (packet->size >= sizeof(xarp_packet_t)) {
xarp_packet_t * arp_packet = (xarp_packet_t *) packet->data;
uint16_t opcode = swap_order16(arp_packet->opcode);
// 检查包的合法性,包括硬件类型、硬件地址长度、协议类型、协议地址长度和操作码
if ((swap_order16(arp_packet->hw_type) != XARP_HW_ETHER) ||
(arp_packet->hw_len != XNET_MAC_ADDR_SIZE) ||
(swap_order16(arp_packet->pro_type) != XNET_PROTOCOL_IP) ||
(arp_packet->pro_len != XNET_IPV4_ADDR_SIZE)
|| ((opcode != XARP_REQUEST) && (opcode != XARP_REPLY))) {
return;
}
// 只处理目标IP地址为自己的ARP请求或响应包
if (!xipaddr_is_equal_buf(&netif_ipaddr, arp_packet->target_ip)) {
return;
}
// 根据操作码进行处理
switch (swap_order16(arp_packet->opcode)) {
case XARP_REQUEST: // 处理ARP请求发送ARP响应并更新ARP表项
xarp_make_response(arp_packet);
update_arp_entry(arp_packet->sender_ip, arp_packet->sender_mac);
break;
case XARP_REPLY: // 处理ARP响应更新ARP表项
update_arp_entry(arp_packet->sender_ip, arp_packet->sender_mac);
break;
}
}
}
```
该函数主要功能是处理接收到的ARP包。首先进行简单的长度判断避免后续字段读取失败造成内存错误。随后检查包的合法性包括硬件类型、硬件地址长度、协议类型、协议地址长度和操作码。APR响应只要求机器处理目标IP地址为自己的ARP请求或响应包所以使用```c if (!xipaddr_is_equal_buf(&netif_ipaddr, arp_packet->target_ip))```来判断。最后根据操作码进行处理分别处理ARP请求和ARP响应
- ARP请求发送ARP响应```c xarp_make_response(...)```并更新ARP表项```c update_arp_entry(...)```
- ARP响应只需要更新ARP表项。
其中,用到的宏```c xipaddr_is_equal_buf()```函数用于比较两个IP地址是否相等实现如下
```c
// 比较IP地址是否相等
#define xipaddr_is_equal_buf(addr, buf) (memcmp(
(addr)->array,
(buf),
XNET_IPV4_ADDR_SIZE
)
== 0
)
```
然后,需要编写上面函数中调用的两个函数:```c xarp_make_response()``````c update_arp_entry()```
```c xarp_make_response()```函数主要功能是输入一个ARP请求包通过此包内的源信息生成对应的ARP响应并发送出去。具体代码如下
```c
/**
* 生成一个ARP响应
* @param arp_packet 接收到的ARP请求包
* @return 生成结果
*/
xnet_err_t xarp_make_response(xarp_packet_t * arp_packet) {
xarp_packet_t* response_packet;
xnet_packet_t * packet = xnet_alloc_for_send(sizeof(xarp_packet_t));
response_packet = (xarp_packet_t *)packet->data;
response_packet->hw_type = swap_order16(XARP_HW_ETHER); // 设置硬件类型为以太网
response_packet->pro_type = swap_order16(XNET_PROTOCOL_IP); // 设置协议类型为IP
response_packet->hw_len = XNET_MAC_ADDR_SIZE; // 设置硬件地址长度
response_packet->pro_len = XNET_IPV4_ADDR_SIZE; // 设置协议地址长度
response_packet->opcode = swap_order16(XARP_REPLY); // 设置操作码为ARP响应
// 复制目标MAC地址
memcpy(response_packet->target_mac, arp_packet->sender_mac, XNET_MAC_ADDR_SIZE);
// 复制目标IP地址
memcpy(response_packet->target_ip, arp_packet->sender_ip, XNET_IPV4_ADDR_SIZE);
// 复制发送方MAC地址
memcpy(response_packet->sender_mac, netif_mac, XNET_MAC_ADDR_SIZE);
// 复制发送方IP地址
memcpy(response_packet->sender_ip, netif_ipaddr.array, XNET_IPV4_ADDR_SIZE);
// 通过以太网发送ARP响应
return ethernet_out_to(XNET_PROTOCOL_ARP, ether_broadcast, packet);
}
```
可以发现此函数与前面的ARP请求函数```c xarp_make_request()```非常相似,只是操作码不同,此处为`XARP_REPLY`其他字段均从源ARP请求报文中获取并填入对应区域。
```c update_arp_entry()```函数主要功能是更新所有ARP表项附带一定的可视化功能。具体代码如下
```c
/**
* 更新ARP表项
* @param src_ip 源IP地址
* @param mac_addr 对应的mac地址
*/
static void update_arp_entry(uint8_t* src_ip, uint8_t* mac_addr) {
for (arp_entry = arp_table;
arp_entry < XARP_CFG_ENTRY_SIZE * sizeof(xarp_entry_t) + arp_table;
arp_entry = arp_entry + sizeof(xarp_entry_t))
{
// 检查ARP表项是否为空或者是否与给定的源IP地址匹配且状态不是有效的
if (arp_entry->state == XARP_ENTRY_FREE ||
( arp_entry->state == XARP_ENTRY_OK
&& xipaddr_is_equal_buf(&arp_entry->ipaddr, src_ip)
))
{
// 更新ARP表项中的IP地址和MAC地址
memcpy(arp_entry->ipaddr.array, src_ip, XNET_IPV4_ADDR_SIZE);
memcpy(arp_entry->macaddr, mac_addr, 6);
printf("learned☝🤓mac addr\n");
for (
int i = 0;
i < sizeof(mac_addr) / sizeof(mac_addr[0]);
++i)
{
printf("%02X%c",
mac_addr[i],
i < sizeof(mac_addr) / sizeof(mac_addr[0]) - 1 ? ':' : '\n'
);
}
// 设置ARP表项状态为有效
arp_entry->state = XARP_ENTRY_OK;
// 设置ARP表项的超时时间
arp_entry->tmo = XARP_CFG_ENTRY_OK_TMO;
// 设置ARP表项的重试次数
arp_entry->retry_cnt = XARP_CFG_MAX_RETRIES;
print_arp_table(); // 打印完整的ARP表
return; // 更新后退出函数
}
}
// 如果ARP表已满采用LRU策略替换最老的表项
arp_entry = arp_table; // 重置arp_entry指向表头
xarp_entry_t* oldest_entry = NULL;
uint32_t oldest_tmo = 0xFFFFFFFF;
for (arp_entry = arp_table;
arp_entry < XARP_CFG_ENTRY_SIZE * sizeof(xarp_entry_t) + arp_table;
arp_entry = arp_entry + sizeof(xarp_entry_t))
{
if (arp_entry->tmo < oldest_tmo) {
oldest_tmo = arp_entry->tmo;
oldest_entry = arp_entry;
}
}
if (oldest_entry != NULL) {
// 更新最老的ARP表项
memcpy(oldest_entry->ipaddr.array, src_ip, XNET_IPV4_ADDR_SIZE);
memcpy(oldest_entry->macaddr, mac_addr, 6);
printf("learned☝🤓mac addr\n");
for (int i = 0; i < sizeof(mac_addr) / sizeof(mac_addr[0]); ++i){
printf("%02X%c", mac_addr[i],
i < sizeof(mac_addr) / sizeof(mac_addr[0]) - 1 ? ':' : '\n');
}
// 设置ARP表项状态为有效
oldest_entry->state = XARP_ENTRY_OK;
// 设置ARP表项的超时时间
oldest_entry->tmo = XARP_CFG_ENTRY_OK_TMO;
// 设置ARP表项的重试次数
oldest_entry->retry_cnt = XARP_CFG_MAX_RETRIES;
print_arp_table(); // 打印完整的ARP表
}
}
```
这个函数很长。它主要功能是更新ARP表项。更新分为两种情况
- ARP表还有空闲表项
- ARP表已满采用LRU策略替换最老的表项
首先函数通过遍历ARP表中的所有表项检查表项是否为空或者是否与给定的源IP地址匹配且状态不是有效的。如果满足条件则更新ARP表项中的IP地址和MAC地址并设置表项状态为有效设置超时时间和重试次数最后会打印完整的ARP表。如果ARP表已满则采用LRU策略替换最老的表项。函数会遍历ARP表找到超时时间最小的表项并更新该表项的IP地址和MAC地址设置表项状态为有效设置超时时间和重试次数最后打印完整的ARP表。
用到的打印函数实现如下:
```c
/**
* 打印完整的ARP表
*/
void print_arp_table() {
printf("\n----ARP Table----\n");
for (arp_entry = arp_table;
arp_entry < XARP_CFG_ENTRY_SIZE * sizeof(xarp_entry_t) + arp_table;
arp_entry = arp_entry + sizeof(xarp_entry_t))
{
if (arp_entry->state != XARP_ENTRY_FREE) {
printf("IP: ");
for (int i = 0; i < XNET_IPV4_ADDR_SIZE; ++i) {
printf("%d%c",
arp_entry->ipaddr.array[i],
i < XNET_IPV4_ADDR_SIZE - 1 ? '.' : '\n'
);
}
printf("MAC: ");
for (int i = 0; i < 6; ++i) {
printf("%02X%c", arp_entry->macaddr[i], i < 5 ? ':' : '\n');
}
printf(
"State: %s\n",
arp_entry->state == XARP_ENTRY_FREE ? "FREE" :
arp_entry->state == XARP_ENTRY_RESOLVING ? "RESOLVING" : "OK"
);
}
}
printf("\n-----------------\n");
}
```
最后需要在以太网帧接收函数中添加ARP报文的处理
```c
/**
* 以太网数据帧输入输出
* @param packet 待处理的包
*/
static void ethernet_in (xnet_packet_t * packet) {
// 至少要比头部数据大
if (packet->size <= sizeof(xether_hdr_t)) {
return;
}
// 根据协议类型分发到不同的处理函数
xether_hdr_t* hdr = (xether_hdr_t*)packet->data;
switch (swap_order16(hdr->protocol)) {
case XNET_PROTOCOL_ARP:
// 移除以太网头部处理ARP协议
remove_header(packet, sizeof(xether_hdr_t));
xarp_in(packet);
break;
case XNET_PROTOCOL_IP: {
break;
}
}
}
```
其中,主要在```c case XNET_PROTOCOL_ARP```中添加了对ARP报文的处理。
在继续之前再次使用Wireshark检验这部分代码编写。重新编译后按照以下流程进行检验
- 开启Wireshark抓包
- 运行本程序;
- 在虚拟机上ping本程序以触发ARP请求
- 查看Wireshark抓包结果和程序输出。
#figure(image("ARP响应.png",format: "png",width: 100%,fit: "stretch"),caption: "ARP请求响应")<figure4>
@figure4 中可以看到ARP响应都发送成功程序输出中也表明学习到了虚拟机的MAC地址说明代码编写正确。
]
=== ARP超时重传
#para[
首先需要定义ARP表项的其他两种状态#footnote[第一种状态已经在@State1 中定义过了。]解析成功、和正在解析即已发出重传的ARP请求报文但还未收到响应
```c
#define XARP_ENTRY_OK 1 // ARP表项解析成功
#define XARP_ENTRY_RESOLVING 2 // ARP表项正在解析
#define XARP_TIMER_PERIOD 1 // ARP扫描周期1s足够
```
然后需要定义超时时间和重试次数:
```c
#define XARP_CFG_ENTRY_OK_TMO (10) // ARP表项超时时间
#define XARP_CFG_ENTRY_PENDING_TMO (2) // ARP表项挂起超时时间
#define XARP_CFG_MAX_RETRIES 4 // ARP表挂起时重试查询次数
```
`xnet_tiny.c`中,`xarp_poll`函数负责定期检查ARP表项的状态并根据需要触发重传。具体实现如下
```c
/**
* 查询ARP表项是否超时超时则重新请求
*/
void xarp_poll(void) {
// 检查ARP定时器是否超时
if (xnet_check_tmo(&arp_timer, XARP_TIMER_PERIOD)) {
for ( arp_entry = arp_table;
arp_entry < XARP_CFG_ENTRY_SIZE * sizeof(xarp_entry_t) + arp_table;
arp_entry = arp_entry + sizeof(xarp_entry_t))
{
switch (arp_entry->state) {
case XARP_ENTRY_RESOLVING:
// 如果ARP表项正在解析中检查超时计数器
if (--arp_entry->tmo == 0) {
// 如果重试次数用完释放ARP表项
if (arp_entry->retry_cnt-- == 0) {
arp_entry->state = XARP_ENTRY_FREE;
}
else {
// 否则继续重试发送ARP请求
xarp_make_request(&arp_entry->ipaddr);
arp_entry->state = XARP_ENTRY_RESOLVING;
arp_entry->tmo = XARP_CFG_ENTRY_PENDING_TMO;
}
}
break;
case XARP_ENTRY_OK:
// 如果ARP表项有效检查超时计数器
if (--arp_entry->tmo == 0) {
// 超时后重新发送ARP请求
xarp_make_request(&arp_entry->ipaddr);
arp_entry->state = XARP_ENTRY_RESOLVING;
arp_entry->tmo = XARP_CFG_ENTRY_PENDING_TMO;
}
break;
}
}
}
}
```
该函数主要功能是定时检查ARP表项的状态具体步骤如下
1. 定时检查:```c xarp_poll()```函数会定期检查ARP表项的状态检查周期由`XARP_TIMER_PERIOD`定义1秒
2. 状态判断:
- 如果表项状态为`XARP_ENTRY_RESOLVING`正在解析中则检查超时计数器。如果超时且重试次数用完则释放该表项否则重新发送ARP请求并重置超时计数器。
- 如果表项状态为`XARP_ENTRY_OK`有效则检查超时计数器。如果超时则重新发送ARP请求并将表项状态设置为`XARP_ENTRY_RESOLVING`
3. 重传ARP请求通过调用`xarp_make_request`函数重新发送ARP请求以获取目标IP地址对应的MAC地址。
下面是用Wireshark抓包验证ARP超时重传的结果。重新编译后直接运行程序在虚拟机上ping本程序以触发ARP请求。本程序学习完成之后每秒钟会发送一次ARP请求。Wireshark抓包结果如下
#figure(image("十秒一个2.png",format: "png",width: 100%,fit: "stretch"),caption: "固定间隔的ARP超时重传")<figure5>
注意@figure5 中左侧的`Time`一列从上到下程序发出的ARP请求的时间依次增加10秒。这表明ARP请求每10秒钟发送一次在上面代码中的这一行定义过的ARP表项超时时间生效ARP请求重传成功。
```c
#define XARP_CFG_ENTRY_OK_TMO (10) // ARP表项超时时间
```
至此ARP协议的实现完成。
]
== 实现IP协议
#para[
以太网之上除了ARP协议还有IP协议。IP协议是网络层协议负责将数据包从源主机传输到目的主机。IP协议的数据包称为IP数据报包含了源IP地址和目的IP地址。
与前面通过抓包来获取ARP数据包的各字段值的方法类似IP数据包各字段值也可以通过抓包获取但更方便的做法是查询RFC文档#footnote[文档地址:#link("https://www.rfc-editor.org/rfc/rfc791")[RFC 791: Internet Protocol]]来获取此处不再展示。下面来实现IP协议。
]
=== 定义IP数据报
#para[
`xnet_tiny.h` 中定义IP数据报的结构体
```c
typedef struct _xip_hdr_t {
uint8_t hdr_len : 4; // 首部长, 4字节为单位
uint8_t version : 4; // 版本号
uint8_t tos; // 服务类型
uint16_t total_len; // 总长度
uint16_t id; // 标识符
uint16_t flags_fragment; // 标志与分段
uint8_t ttl; // 存活时间
uint8_t protocol; // 上层协议
uint16_t hdr_checksum; // 首部校验和
uint8_t src_ip[XNET_IPV4_ADDR_SIZE]; // 源IP
uint8_t dest_ip[XNET_IPV4_ADDR_SIZE]; // 目标IP
} xip_hdr_t;
```
该结构体定义了IP数据报的各个字段包括
- `hdr_len`IP头部的长度以4字节为单位。
- `version`IP版本号通常为IPv4值为4
- `tos`:服务类型,用于指定数据报的优先级。
- `total_len`IP数据报的总长度。
- `id`标识符用于标识IP数据报。
- `flags_fragment`标志和分段信息用于IP分片。
- `ttl`:生存时间,用于防止数据报在网络中无限循环。
- `protocol`上层协议类型如ICMP、TCP或UDP。
- `hdr_checksum`IP头部的校验和用于检测数据报是否损坏。
- `src_ip` `dest_ip`源IP地址和目标IP地址。
]
=== 实现IP输入
#para[
IP输入函数 `xip_in` 负责处理接收到的IP数据报。在 `xnet_tiny.c` 中实现该函数:
```c
void xip_in(xnet_packet_t * packet) {
xip_hdr_t* iphdr = (xip_hdr_t*)packet->data;
uint32_t total_size, header_size;
uint16_t pre_checksum;
xipaddr_t src_ip;
// 检查IP版本号是否为IPv4
if (iphdr->version != XNET_VERSION_IPV4) {
return;
}
// 检查头部长度和总长度是否符合要求
header_size = iphdr->hdr_len * 4;
total_size = swap_order16(iphdr->total_len);
if (
(header_size < sizeof(xip_hdr_t))
|| ((total_size < header_size)
|| (packet->size < total_size))
)
return;
// 校验头部的校验和是否正确
pre_checksum = iphdr->hdr_checksum;
iphdr->hdr_checksum = 0;
if (pre_checksum != checksum16((uint16_t*)iphdr, header_size, 0, 1)) {
return;
}
// 检查目标IP地址是否为本机IP
if (!xipaddr_is_equal_buf(&netif_ipaddr, iphdr->dest_ip)) {
return;
}
// 根据协议类型分发到不同的处理函数
xipaddr_from_buf(&src_ip, iphdr->src_ip);
switch(iphdr->protocol) {
case XNET_PROTOCOL_ICMP:
remove_header(packet, header_size);
xicmp_in(&src_ip, packet);
break;
default:
break;
}
}
```
函数逻辑、功能比较简单概括如下检查IP版本号是否为IPv4。然后验证IP头部的长度和总长度是否符合要求。再校验IP头部的校验和是否正确、检查目标IP地址是否为本机IP。最后根据上层协议类型如ICMP将数据报分发到相应的处理函数。
]
=== 实现IP输出
#para[
IP输出函数 `xip_out` 负责发送IP数据报。在 `xnet_tiny.c` 中,我们实现了该函数:
```c
xnet_err_t xip_out(xnet_protocol_t protocol, xipaddr_t* dest_ip, xnet_packet_t * packet)
{
static uint32_t ip_packet_id = 0; // 静态变量用于生成唯一的IP包ID
xip_hdr_t * iphdr;
add_header(packet, sizeof(xip_hdr_t)); // 添加IP头部
iphdr = (xip_hdr_t*)packet->data; // 获取IP头部指针
iphdr->version = XNET_VERSION_IPV4; // 设置IP版本号为IPv4
iphdr->hdr_len = sizeof(xip_hdr_t) / 4; // 设置IP头部长度
iphdr->tos = 0; // 设置服务类型
iphdr->total_len = swap_order16(packet->size); // 设置总长度
iphdr->id = swap_order16(ip_packet_id); // 设置包ID
iphdr->flags_fragment = 0; // 设置标志和片偏移
iphdr->ttl = XNET_IP_DEFAULT_TTL; // 设置生存时间
iphdr->protocol = protocol; // 设置上层协议类型
memcpy(iphdr->dest_ip, dest_ip->array, XNET_IPV4_ADDR_SIZE); // 设置目标IP地址
// 设置源IP地址
memcpy(iphdr->src_ip, netif_ipaddr.array, XNET_IPV4_ADDR_SIZE);
iphdr->hdr_checksum = 0; // 初始化校验和字段
// 计算并设置校验和
iphdr->hdr_checksum = checksum16((uint16_t *)iphdr, sizeof(xip_hdr_t), 0, 1);
ip_packet_id++; // 增加包ID
return ethernet_out(dest_ip, packet); // 通过以太网发送IP包
}
```
该函数的主要功能是:
1. 添加IP头部到数据报中。
2. 设置IP头部的各个字段包括版本号、头部长度、总长度、包ID、生存时间、上层协议类型、源IP地址和目标IP地址。
3. 计算并设置IP头部的校验和。
4. 通过以太网发送IP数据报。
]
== 实现ICMP协议
#para[
实现了ARP和IP协议之后下面来实现ICMP协议。ICMP协议是网络层协议用于在IP网络中传递控制消息。ICMP数据报的数据部分包含了ICMP报文的类型、代码和校验和等字段。实现ICMP的主要目的在于实现ping功能即实现ICMP的ping响应。
]
=== 定义ICMP数据报
#para[
ICMPInternet Control Message Protocol是网络层协议用于在IP网络中传递控制消息。在 `xnet_tiny.h` 我们定义了ICMP数据报的结构体
```c
typedef struct _xicmp_hdr_t {
uint8_t type; // 类型
uint8_t code; // 代码
uint16_t checksum; // ICMP报文的校验和
uint16_t id; // 标识符
uint16_t seq; // 序号
} xicmp_hdr_t;
```
该结构体定义了ICMP数据报的各个字段包括
- `type`ICMP消息类型例如回显请求`8`)和回显响应(`0`)。
- `code`ICMP消息代码用于进一步细分消息类型。
- `checksum`ICMP报文的校验和用于检测报文是否损坏。
- `id` `seq`:标识符和序号,用于匹配请求和响应。
此外我们还定义了ICMP消息类型的常量
```c
#define XICMP_CODE_ECHO_REQUEST 8 // 回显请求
#define XICMP_CODE_ECHO_REPLY 0 // 回显响应
```
]
=== 实现ICMP输入
#para[
ICMP输入函数 `xicmp_in` 负责处理接收到的ICMP数据报。在 `xnet_tiny.c` 中,我们实现了该函数:
```c
void xicmp_in(xipaddr_t *src_ip, xnet_packet_t * packet) {
xicmp_hdr_t* icmphdr = (xicmp_hdr_t *)packet->data; // 获取ICMP头部指针
if (
(packet->size >= sizeof(xicmp_hdr_t))
&& (icmphdr->type == XICMP_CODE_ECHO_REQUEST)
)
{
reply_icmp_request(icmphdr, src_ip, packet); // 如果是ECHO请求发送ECHO回复
}
}
```
该函数的主要功能是:
1. 检查接收到的ICMP数据报是否完整。
2. 如果ICMP消息类型为回显请求`XICMP_CODE_ECHO_REQUEST`),则调用 `reply_icmp_request` 函数发送回显响应。
]
=== 实现ICMP-ping响应
#para[
ICMP-ping响应函数 `reply_icmp_request` 负责生成并发送ICMP回显响应。在 `xnet_tiny.c` 中,我们实现了该函数:
```c
static xnet_err_t reply_icmp_request( xicmp_hdr_t * icmp_hdr,
xipaddr_t* src_ip,
xnet_packet_t * packet)
{
xicmp_hdr_t * replay_hdr;
xnet_packet_t * tx = xnet_alloc_for_send(packet->size);
replay_hdr = (xicmp_hdr_t *)tx->data; // 获取ICMP头部指针
replay_hdr->type = XICMP_CODE_ECHO_REPLY; // 设置ICMP类型为ECHO回复
replay_hdr->code = 0; // 设置代码为0
replay_hdr->id = icmp_hdr->id; // 复制ID
replay_hdr->seq = icmp_hdr->seq; // 复制序列号
replay_hdr->checksum = 0; // 初始化校验和字段
// 复制数据部分
memcpy(
((uint8_t *)replay_hdr)+ sizeof(xicmp_hdr_t),
((uint8_t *)icmp_hdr) + sizeof(xicmp_hdr_t),
packet->size - sizeof(xicmp_hdr_t)
);
// 计算校验和
replay_hdr->checksum = checksum16((uint16_t*)replay_hdr, tx->size, 0, 1);
return xip_out(XNET_PROTOCOL_ICMP, src_ip, tx); // 发送ICMP回复包
}
```
该函数的主要功能是:
1. 分配一个新的数据包用于发送ICMP回显响应。
2. 设置ICMP回显响应的各个字段包括类型、代码、ID、序列号和校验和。
3. 复制原始ICMP请求的数据部分到响应中。
4. 计算并设置ICMP回显响应的校验和。
5. 通过IP层发送ICMP回显响应。
通过该函数我们可以实现对ICMP-ping请求的响应从而支持基本的网络连通性测试。
下面进行测试。重新编译后,按照以下流程进行测试:
- 开启Wireshark抓包
- 运行本程序;
- 在虚拟机上ping本程序以触发ICMP-ping请求
- 在虚拟机上查看ping结果看是否ping通
- 查看Wireshark抓包结果见下页
#figure(image("ping通.png",format: "png",width: 100%,fit: "stretch"),caption: "ICMP-ping响应")<figure6>
@figure6 中可以看到ICMP-ping响应发送成功程序输出中也表明学习到了虚拟机的MAC地址说明代码编写正确。
]
== 关于多ARP表项
#para[
代码在定义相关数据结构时(见@multiple_entry 已经考虑到了多ARP表项的情况。在函数的具体实现中均是使用循环遍历整个ARP表来进行表项的操作。
@figure4@figure6 中的程序输出中均有2个表项对同一个ARP表项的不同状态。如果考虑再添加一台虚拟机则可以在输出中看到更多表项。但本次实验所用物理机内存有限无法同时运行2个虚拟机所以不再演示。
]
= 实验总结
== 内容总结
#para[
本次实验主要围绕ARP协议的实现展开通过编写程序完善了TCP/IP协议栈的ARP协议部分。实验内容包括ARP的初始化、无回报ARP的生成、ARP的输入处理以及ARP的超时重新请求机制。在基础任务中成功实现了ARP协议的核心功能包括ARP请求与响应的构建与解析、ARP缓存表的管理等。此外还完成了拓展任务实现了多个ARP表项的管理以及IP层的输入输出处理。
在实验过程中首先通过Wireshark抓包分析了ARP报文的结构并基于此定义了ARP报文的数据结构和相关函数。接着实现了ARP报文的发送与接收功能包括ARP请求的生成与广播、ARP响应的处理以及ARP缓存表的更新。通过定时器机制实现了ARP表项的超时重传功能确保了ARP缓存的准确性和及时性。
在完成ARP协议的基础上进一步实现了IP协议和ICMP协议。通过定义IP数据报和ICMP数据报的结构实现了IP层的输入输出功能并成功实现了ICMP的ping响应功能。实验结果表明ARP、IP和ICMP协议的功能均得到了正确实现能够有效支持网络设备之间的通信。
]
== 心得感悟
#para[
通过本次实验我深刻理解了ARP协议的工作原理及其在网络通信中的重要作用。ARP协议作为TCP/IP协议栈中的重要组成部分负责将IP地址解析为MAC地址是网络设备之间通信的基础。通过亲手实现ARP协议的核心功能我不仅加深了对ARP协议的理解还掌握了网络协议栈的实现方法。
在实验过程中我遇到了一些挑战例如如何正确解析ARP报文、如何管理ARP缓存表以及如何处理ARP超时重传等。通过查阅资料、分析抓包数据以及反复调试代码我逐步解决了这些问题并成功实现了ARP协议的功能。这让我认识到网络协议的实现不仅需要扎实的理论基础还需要细致的调试和问题解决能力。
此外通过实现IP和ICMP协议我进一步了解了网络层协议的工作原理。IP协议负责数据包的传输而ICMP协议则用于传递控制消息。通过实现ICMP的ping响应功能我掌握了ICMP协议的基本实现方法并理解了其在网络连通性测试中的应用。
总的来说本次实验让我对TCP/IP协议栈有了更深入的理解并提升了我的编程能力和网络协议分析能力。这些知识和技能对我今后学习更复杂的网络协议以及从事网络相关工作具有重要意义。
]
#show heading: it => box(width: 100%)[
#v(0.50em)
#set text(font: hei)
// #counter(heading).display()
// #h(0.5em)
#it.body
]
#pagebreak()
#bibliography("ref.yml",full: true,title: "参考文献",style:"gb-7714-2015-numeric")
/*
根据这个网站的格式示范https://github.com/typst/hayagriva/blob/main/docs/file-format.md
为这个网页生成.yml文件
https://blog.csdn.net/jxjdhdnd/article/details/138009187
*/

Binary file not shown.

After

Width:  |  Height:  |  Size: 323 KiB

44
network/arpicmplab/arp/ref.yml Executable file
View File

@ -0,0 +1,44 @@
cmake_tutorial_csdn:
type: Web
title: "【一学就会】C++编译工具链——基于VSCode的CMake、make与g++简单理解与应用示例"
author: "未知作者"
url:
value: "https://blog.csdn.net/weixin_46248871/article/details/137500744"
date: 2024-12-31
abstract: "本文详细介绍了CMake、make与g++的基本概念、优劣比较以及应用示例包括工具安装配置、CMake使用示例、g++使用教程等。"
cmake_detailed_tutorial_csdn:
type: Web
title: "cmake使用详细教程日常使用这一篇就足够了"
author: "李吱恩"
url:
value: "https://blog.csdn.net/iuu77/article/details/129229361"
date: 2023-11-28
abstract: "本文为博主原创文章提供了cmake的详细使用教程包括cmake安装、使用cmake配合程序编译的多种情况如单个源文件程序编译、多个源文件、头文件在不同文件夹等场景。"
rfc791_internet_protocol:
type: Web
title: "INTERNET PROTOCOL"
author: "Jon Postel"
url:
value: "https://www.rfc-editor.org/rfc/rfc791"
date: 1981-09
abstract: "RFC 791 定义了互联网协议IP这是TCP/IP协议栈中的核心协议之一负责在网络中传输数据包。文档详细介绍了IP协议的规范和操作。"
windows_network_commands_cnblogs:
type: Web
title: "windows网络命令ping、ipconfig、tracert、netstat、arp"
author: "刘玉坦"
url:
value: "https://www.cnblogs.com/liuyutan/p/13289747.html"
date: 2024-12-31
abstract: "本文介绍了Windows系统中常用的网络诊断命令包括ping、ipconfig、tracert、netstat和arp以及它们的使用场景和参数说明。"
bilibili_tcp_ip_stack:
type: Web
title: "c03.00 IP层的输入处理(2)"
author: "哔哩哔哩用户"
url:
value: "https://www.bilibili.com/video/BV1KL4y1P7vG"
date: 2024-12-31
abstract: "视频教程完全从0开始手写一个超轻量级的TCP/IP网络协议栈支持以太网、ARP、IP、UDP、TCP协议并实现了一个超小型的HTTP服务器。"

397
network/arpicmplab/arp/tmp.md Executable file
View File

@ -0,0 +1,397 @@
### ARP超时重传
在ARP协议中如果某个ARP表项在一定时间内没有收到响应或者表项的状态变为无效系统会触发ARP超时重传机制。这一机制确保在网络中能够及时更新或重新获取目标设备的MAC地址。
#### 超时重传的实现
`xnet_tiny.c`中,`xarp_poll`函数负责定期检查ARP表项的状态并根据需要触发重传。具体实现如下
```c
/
* 查询ARP表项是否超时,超时则重新请求
*/
void xarp_poll(void) {
// 检查ARP定时器是否超时
if (xnet_check_tmo(&arp_timer, XARP_TIMER_PERIOD)) {
for (arp_entry = arp_table; arp_entry < XARP_CFG_ENTRY_SIZE * sizeof(xarp_entry_t) + arp_table; arp_entry = arp_entry + sizeof(xarp_entry_t)) {
switch (arp_entry->state) {
case XARP_ENTRY_RESOLVING:
// 如果ARP表项正在解析中检查超时计数器
if (--arp_entry->tmo == 0) {
// 如果重试次数用完释放ARP表项
if (arp_entry->retry_cnt-- == 0) {
arp_entry->state = XARP_ENTRY_FREE;
}
else {
// 否则继续重试发送ARP请求
xarp_make_request(&arp_entry->ipaddr);
arp_entry->state = XARP_ENTRY_RESOLVING;
arp_entry->tmo = XARP_CFG_ENTRY_PENDING_TMO;
}
}
break;
case XARP_ENTRY_OK:
// 如果ARP表项有效检查超时计数器
if (--arp_entry->tmo == 0) {
// 超时后重新发送ARP请求
xarp_make_request(&arp_entry->ipaddr);
arp_entry->state = XARP_ENTRY_RESOLVING;
arp_entry->tmo = XARP_CFG_ENTRY_PENDING_TMO;
}
break;
}
}
}
}
```
#### 超时重传的流程
1. 定时检查:`xarp_poll`函数会定期检查ARP表项的状态检查周期由`XARP_TIMER_PERIOD`定义默认为1秒
2. 状态判断:
- 如果表项状态为`XARP_ENTRY_RESOLVING`正在解析中则检查超时计数器。如果超时且重试次数用完则释放该表项否则重新发送ARP请求并重置超时计数器。
- 如果表项状态为`XARP_ENTRY_OK`有效则检查超时计数器。如果超时则重新发送ARP请求并将表项状态设置为`XARP_ENTRY_RESOLVING`
3. 重传ARP请求通过调用`xarp_make_request`函数重新发送ARP请求以获取目标IP地址对应的MAC地址。
#### 超时重传的意义
ARP超时重传机制确保了在网络中即使某些设备暂时不可达系统也能通过多次尝试获取其MAC地址。这种机制在网络环境不稳定或设备频繁上下线的情况下尤为重要能够有效避免因ARP表项失效导致的通信中断。
#### 实验验证
为了验证ARP超时重传机制的正确性可以通过以下步骤进行测试
1. 启动程序运行程序并确保ARP表项初始化完成。
2. 模拟超时在ARP表项超时后观察是否触发了重传机制。
3. 抓包分析使用Wireshark抓包工具查看是否在超时后重新发送了ARP请求。
通过以上步骤可以验证ARP超时重传机制是否按预期工作。
```typ
#figure(image("ARP超时重传.png",format: "png",width: 100%,fit: "stretch"),caption: "ARP超时重传抓包结果")<figure5>
```
@figure5 中可以看到ARP请求在超时后重新发送说明超时重传机制工作正常。
以下是 `=== 定义IP数据报``=== 实现IP输入``=== 实现IP输出` 部分的 Markdown 内容:
```markdown
=== 定义IP数据报
IP数据报是网络层协议的核心数据结构包含了源IP地址、目标IP地址以及上层协议类型等信息。在 `xnet_tiny.h`我们定义了IP数据报的结构体
```c
typedef struct _xip_hdr_t {
uint8_t hdr_len : 4; // 首部长, 4字节为单位
uint8_t version : 4; // 版本号
uint8_t tos; // 服务类型
uint16_t total_len; // 总长度
uint16_t id; // 标识符
uint16_t flags_fragment; // 标志与分段
uint8_t ttl; // 存活时间
uint8_t protocol; // 上层协议
uint16_t hdr_checksum; // 首部校验和
uint8_t src_ip[XNET_IPV4_ADDR_SIZE]; // 源IP
uint8_t dest_ip[XNET_IPV4_ADDR_SIZE]; // 目标IP
} xip_hdr_t;
```
该结构体定义了IP数据报的各个字段包括
- `hdr_len`IP头部的长度以4字节为单位。
- `version`IP版本号通常为IPv4值为4
- `tos`:服务类型,用于指定数据报的优先级。
- `total_len`IP数据报的总长度。
- `id`标识符用于标识IP数据报。
- `flags_fragment`标志和分段信息用于IP分片。
- `ttl`:生存时间,用于防止数据报在网络中无限循环。
- `protocol`上层协议类型如ICMP、TCP或UDP。
- `hdr_checksum`IP头部的校验和用于检测数据报是否损坏。
- `src_ip``dest_ip`源IP地址和目标IP地址。
=== 实现IP输入
IP输入函数 `xip_in` 负责处理接收到的IP数据报。在 `xnet_tiny.c` 中,我们实现了该函数:
```c
void xip_in(xnet_packet_t * packet) {
xip_hdr_t* iphdr = (xip_hdr_t*)packet->data;
uint32_t total_size, header_size;
uint16_t pre_checksum;
xipaddr_t src_ip;
// 检查IP版本号是否为IPv4
if (iphdr->version != XNET_VERSION_IPV4) {
return;
}
// 检查头部长度和总长度是否符合要求
header_size = iphdr->hdr_len * 4;
total_size = swap_order16(iphdr->total_len);
if ((header_size < sizeof(xip_hdr_t)) || ((total_size < header_size) || (packet->size < total_size))) {
return;
}
// 校验头部的校验和是否正确
pre_checksum = iphdr->hdr_checksum;
iphdr->hdr_checksum = 0;
if (pre_checksum != checksum16((uint16_t*)iphdr, header_size, 0, 1)) {
return;
}
// 检查目标IP地址是否为本机IP
if (!xipaddr_is_equal_buf(&netif_ipaddr, iphdr->dest_ip)) {
return;
}
// 根据协议类型分发到不同的处理函数
xipaddr_from_buf(&src_ip, iphdr->src_ip);
switch(iphdr->protocol) {
case XNET_PROTOCOL_ICMP:
remove_header(packet, header_size);
xicmp_in(&src_ip, packet);
break;
default:
break;
}
}
```
该函数的主要功能是:
1. 检查IP版本号是否为IPv4。
2. 检查IP头部的长度和总长度是否符合要求。
3. 校验IP头部的校验和是否正确。
4. 检查目标IP地址是否为本机IP。
5. 根据上层协议类型如ICMP将数据报分发到相应的处理函数。
=== 实现IP输出
IP输出函数 `xip_out` 负责发送IP数据报。在 `xnet_tiny.c` 中,我们实现了该函数:
```c
xnet_err_t xip_out(xnet_protocol_t protocol, xipaddr_t* dest_ip, xnet_packet_t * packet) {
static uint32_t ip_packet_id = 0; // 静态变量用于生成唯一的IP包ID
xip_hdr_t * iphdr;
add_header(packet, sizeof(xip_hdr_t)); // 添加IP头部
iphdr = (xip_hdr_t*)packet->data; // 获取IP头部指针
iphdr->version = XNET_VERSION_IPV4; // 设置IP版本号为IPv4
iphdr->hdr_len = sizeof(xip_hdr_t) / 4; // 设置IP头部长度
iphdr->tos = 0; // 设置服务类型
iphdr->total_len = swap_order16(packet->size); // 设置总长度
iphdr->id = swap_order16(ip_packet_id); // 设置包ID
iphdr->flags_fragment = 0; // 设置标志和片偏移
iphdr->ttl = XNET_IP_DEFAULT_TTL; // 设置生存时间
iphdr->protocol = protocol; // 设置上层协议类型
memcpy(iphdr->dest_ip, dest_ip->array, XNET_IPV4_ADDR_SIZE); // 设置目标IP地址
memcpy(iphdr->src_ip, netif_ipaddr.array, XNET_IPV4_ADDR_SIZE); // 设置源IP地址
iphdr->hdr_checksum = 0; // 初始化校验和字段
iphdr->hdr_checksum = checksum16((uint16_t *)iphdr, sizeof(xip_hdr_t), 0, 1); // 计算并设置校验和
ip_packet_id++; // 增加包ID
return ethernet_out(dest_ip, packet); // 通过以太网发送IP包
}
```
该函数的主要功能是:
1. 添加IP头部到数据报中。
2. 设置IP头部的各个字段包括版本号、头部长度、总长度、包ID、生存时间、上层协议类型、源IP地址和目标IP地址。
3. 计算并设置IP头部的校验和。
4. 通过以太网发送IP数据报。
```
### 说明:
1. 代码块:使用 ```c 插入代码块,并指定语言为 C。
2. 标题:使用 `===` 表示三级标题。
3. 段落直接编写文本内容Markdown 会自动处理段落格式。
将此内容插入到 `main.txt` 文件的适当位置即可。
以下是 `=== 定义ICMP数据报`、`=== 实现ICMP输入` 和 `=== 实现ICMP-ping响应` 部分的 Typst 代码:
```typ
=== 定义ICMP数据报
#para[
ICMPInternet Control Message Protocol是网络层协议用于在IP网络中传递控制消息。在 `xnet_tiny.h` 中我们定义了ICMP数据报的结构体
#raw(block: true, lang: "c")[
```c
typedef struct _xicmp_hdr_t {
uint8_t type; // 类型
uint8_t code; // 代码
uint16_t checksum; // ICMP报文的校验和
uint16_t id; // 标识符
uint16_t seq; // 序号
} xicmp_hdr_t;
```
]
该结构体定义了ICMP数据报的各个字段包括
- `type`ICMP消息类型例如回显请求`8`)和回显响应(`0`)。
- `code`ICMP消息代码用于进一步细分消息类型。
- `checksum`ICMP报文的校验和用于检测报文是否损坏。
- `id` 和 `seq`:标识符和序号,用于匹配请求和响应。
此外我们还定义了ICMP消息类型的常量
#raw(block: true, lang: "c")[
```c
#define XICMP_CODE_ECHO_REQUEST 8 // 回显请求
#define XICMP_CODE_ECHO_REPLY 0 // 回显响应
```
]
]
=== 实现ICMP输入
#para[
ICMP输入函数 `xicmp_in` 负责处理接收到的ICMP数据报。在 `xnet_tiny.c` 中,我们实现了该函数:
#raw(block: true, lang: "c")[
```c
void xicmp_in(xipaddr_t *src_ip, xnet_packet_t * packet) {
xicmp_hdr_t* icmphdr = (xicmp_hdr_t *)packet->data; // 获取ICMP头部指针
if ((packet->size >= sizeof(xicmp_hdr_t)) && (icmphdr->type == XICMP_CODE_ECHO_REQUEST)) {
reply_icmp_request(icmphdr, src_ip, packet); // 如果是ECHO请求发送ECHO回复
}
}
```
]
该函数的主要功能是:
1. 检查接收到的ICMP数据报是否完整。
2. 如果ICMP消息类型为回显请求`XICMP_CODE_ECHO_REQUEST`),则调用 `reply_icmp_request` 函数发送回显响应。
]
=== 实现ICMP-ping响应
#para[
ICMP-ping响应函数 `reply_icmp_request` 负责生成并发送ICMP回显响应。在 `xnet_tiny.c` 中,我们实现了该函数:
#raw(block: true, lang: "c")[
```c
static xnet_err_t reply_icmp_request(xicmp_hdr_t * icmp_hdr, xipaddr_t* src_ip, xnet_packet_t * packet) {
xicmp_hdr_t * replay_hdr;
xnet_packet_t * tx = xnet_alloc_for_send(packet->size);
replay_hdr = (xicmp_hdr_t *)tx->data; // 获取ICMP头部指针
replay_hdr->type = XICMP_CODE_ECHO_REPLY; // 设置ICMP类型为ECHO回复
replay_hdr->code = 0; // 设置代码为0
replay_hdr->id = icmp_hdr->id; // 复制ID
replay_hdr->seq = icmp_hdr->seq; // 复制序列号
replay_hdr->checksum = 0; // 初始化校验和字段
memcpy(((uint8_t *)replay_hdr) + sizeof(xicmp_hdr_t), ((uint8_t *)icmp_hdr) + sizeof(xicmp_hdr_t),
packet->size - sizeof(xicmp_hdr_t)); // 复制数据部分
replay_hdr->checksum = checksum16((uint16_t*)replay_hdr, tx->size, 0, 1); // 计算校验和
return xip_out(XNET_PROTOCOL_ICMP, src_ip, tx); // 发送ICMP回复包
}
```
]
该函数的主要功能是:
1. 分配一个新的数据包用于发送ICMP回显响应。
2. 设置ICMP回显响应的各个字段包括类型、代码、ID、序列号和校验和。
3. 复制原始ICMP请求的数据部分到响应中。
4. 计算并设置ICMP回显响应的校验和。
5. 通过IP层发送ICMP回显响应。
通过该函数我们可以实现对ICMP-ping请求的响应从而支持基本的网络连通性测试。
]
```
### 说明:
1. 代码块:使用 `#raw(block: true, lang: "c")` 插入代码块,并指定语言为 C。
2. 标题:使用 `===` 表示三级标题。
3. 段落:使用 `#para[]` 包裹段落内容。
将此代码插入到 `main.txt` 文件的适当位置即可。
6 实验原理及方案
ARP地址解析协议是 TCP/IP 协议族中用于将 IP 地址解析为 MAC 地址的重要协议。IP 通信依赖于数据链路层的硬件地址MAC 地址),而 ARP 负责动态地将网络层的 IP 地址转换为对应的数据链路层 MAC 地址从而实现设备间的通信。ARP 协议的实现主要包括发送 ARP 请求、接收并处理 ARP 响应、更新 ARP 缓存、以及缓存超时机制。
本次实验围绕 TCP/IP 协议栈的 ARP 协议的实现这一问题展开,要求学员在理解 ARP 协议原理的基础上,深入探究 ARP 的技术细节,动手实现 ARP 协议的 Python 程序。
### 1ARP 的初始化
在一个典型的局域网中,设备通过 IP 地址进行网络层通信,但 IP 地址并不能直接用于数据链路层传输。以太网等数据链路层协议使用 MAC 地址进行通信,因此,发送设备需要将目标 IP 地址解析为 MAC 地址才能发送数据帧。
如果该设备的 ARP 缓存中没有目标设备的 MAC 地址映射,它会广播 ARP 请求,询问网络上哪个设备持有特定的 IP 地址。ARP 请求是一个以太网层的广播包,发送到子网内所有设备,只有持有目标 IP 地址的设备才会进行响应。
ARP 初始化的过程是设备发现并解析网络中其他设备的关键步骤。ARP 请求包含源设备的 IP 地址和 MAC 地址,而目标设备通过 ARP 响应提供其对应的 MAC 地址。这个机制确保设备能够通过网络层IP 地址和链路层MAC 地址)之间建立正确的映射关系。
### 2无回报 ARP 的生成
无回报 ARPGratuitous ARP又称为“主动 ARP”或“自愿 ARP”是一种特殊的 ARP 操作。与典型的 ARP 请求不同,无回报 ARP 并不是为了解析目标设备的 MAC 地址,而是设备主动向网络发送广播 ARP 包,通常用于更新网络中的 IP-MAC 映射关系、检测 IP 地址冲突等。
无回报 ARP 是设备主动广播自身的 IP 地址和 MAC 地址,不带有显式的 ARP 请求和响应互动。其主要目的是通知网络中其他设备更新其 ARP 缓存表中的信息。这种情况下,设备并不期待其他设备回应。它是单向广播的,通常被用于下列几种情况:
- 更新网络中的 ARP 表:当设备的 MAC 地址或 IP 地址发生变动时,可以主动发送无回报 ARP以便通知网络中其他设备更新其 ARP 缓存。
- IP 冲突检测:设备在启动时,通过发送无回报 ARP 来检测是否有其他设备占用了相同的 IP 地址。如果另一台设备使用了相同的 IP 地址,它会回应此 ARP 广播,从而帮助设备检测到 IP 冲突。
- 负载均衡器和高可用性系统:当系统切换主备设备时,备设备通常会发送无回报 ARP 来通知网络中的所有节点其 IP-MAC 映射已经改变,避免继续向已下线的设备发送数据。
无回报 ARP 的生成过程如下:
1. 生成 ARP 广播包:设备在确定需要广播自身 IP-MAC 映射时,会生成一个 ARP 广播包。该包包含设备自身的 IP 地址和 MAC 地址,并且目标硬件地址设置为全 0因为无回报 ARP 并不是请求对方设备的 MAC 地址,而是向网络中的所有设备广播自身的信息。
2. 设置操作码为 ARP 请求:尽管无回报 ARP 是主动广播,但它在帧结构中被标记为 ARP 请求(操作码为 1这使得网络中的其他设备会将其视为一种信息广播用于更新 ARP 缓存。
3. 发送广播ARP 广播包通过以太网层进行传输,目标 MAC 地址为 FF:FF:FF:FF:FF:FF即局域网内的所有设备都可以接收到此广播。
4. 网络中的设备处理:网络中所有收到此广播的设备会检查 ARP 包中的发送方 IP 地址和 MAC 地址,并将其更新到本地的 ARP 缓存表中。这样,即使该 IP 地址之前未出现在这些设备的 ARP 表中,它们也会记录并更新新的映射。
### 3ARP 的输入处理
ARP地址解析协议的输入处理指的是设备在接收到 ARP 请求或响应时,如何对该 ARP 报文进行解析和处理,并据此更新设备的 ARP 缓存或进一步采取必要的网络行为。ARP 输入处理的核心任务是解析报文,更新 ARP 缓存,并根据报文类型采取不同的操作。
在这部分有以下步骤:
- 接收 ARP 报文:设备通过网络接口接收到 ARP 报文,无论是广播还是单播形式。这些 ARP 报文可以是 ARP 请求、ARP 响应,或者是无回报 ARP。
- 解析 ARP 报文:设备对 ARP 报文进行解析,提取其中的关键信息。
- 检查报文有效性:设备检查 ARP 报文的有效性,包括检查硬件类型是否为以太网、协议类型是否为 IPv4、操作码是否为合法的请求或响应。如果报文不符合 ARP 协议规定,设备将丢弃该报文。
- 更新 ARP 缓存:根据 ARP 报文中的信息,设备更新自己的 ARP 缓存表。设备通常会把报文中的发送方 IP 地址和发送方 MAC 地址映射记录下来,以便将来进行快速的 IP 到 MAC 地址解析。
- 据操作码进行处理:不同类型的 ARP 报文有不同的处理方式:
- 如果接收到的是 ARP 请求,设备需要检查目标 IP 地址是否与自身的 IP 地址匹配,如果匹配,则需要发送一个 ARP 响应包,告知请求设备自己的 MAC 地址。
- 如果接收到的是 ARP 响应,设备会根据响应包中的信息,更新或添加到 ARP 缓存表,并不再发送进一步的响应。
- 如果接收到的是无回报 ARP设备会将报文中的 IP-MAC 映射记录下来,以更新其 ARP 缓存。
### 4ARP 的超时重新请求机制
ARP地址解析协议的超时重新请求机制指的是设备在尝试解析某个 IP 地址到 MAC 地址时,若未能在设定的时间内收到响应,会采取的重发 ARP 请求的策略。这种机制旨在保证网络设备在通信中能够及时获取目标设备的 MAC 地址,并维持 ARP 缓存的准确性。
ARP 缓存存储的是 IP 地址与 MAC 地址之间的映射关系。在通信过程中,网络设备通常会先查询 ARP 缓存以查找目标设备的 MAC 地址。如果缓存中存在该 IP 地址的记录,设备会直接使用缓存中的 MAC 地址进行通信;如果没有找到相应记录,设备会发出 ARP 请求,广播请求目标 IP 地址对应的 MAC 地址。
如果设备在发送 ARP 请求后,未能在指定的时间内收到 ARP 响应,它会认为该 ARP 请求失败。这时,设备会重新发送 ARP 请求,通常会进行一定次数的重发,以确保能够成功解析目标设备的 MAC 地址。
步骤如下:
1. 发送 ARP 请求:当设备需要与一个目标 IP 地址进行通信时,它首先会查询 ARP 缓存表。如果缓存中没有该 IP 地址的对应条目,设备会发出一个 ARP 请求,以广播方式在本地网络中请求目标设备的 MAC 地址。
2. 等待响应:设备在发送 ARP 请求后,进入等待状态。在这个状态下,设备会等待目标设备的 ARP 响应,通常是几百毫秒到几秒的时间(具体取决于设备的实现和网络情况)。
3. 超时判断:如果在规定的时间内设备没有收到目标设备的 ARP 响应,它会触发超时事件,认为该请求失败。此时,设备进入重新请求机制,准备发出新的 ARP 请求。
4. 重发 ARP 请求:超时后,设备会重新发送 ARP 请求,再次请求目标 IP 地址的 MAC 地址。这个过程通常会重复数次,直到收到响应或者达到最大重试次数为止。设备之间的重试次数和重试间隔时间是预先设定的,例如,设备可能设置为重试 3 到 5 次,每次间隔 1 秒。
5. 处理无响应的情况:如果设备在多次重发后,依然没有收到 ARP 响应,它将放弃请求,并在上层协议(如 IP、TCP 或 UDP层上返回错误表明目标设备不可达。这通常会导致应用层超时或连接失败。设备可能会记录这一信息并在稍后再尝试通信时重新发起 ARP 请求。
6. ARP 缓存条目的超时:即使设备成功解析了目标设备的 MAC 地址ARP 缓存中的条目也并非永久有效。每个 ARP 条目都有一个生存时间TTL通常为几分钟到几十分钟。超过这个时间后如果该条目未被更新设备会将其删除。当设备再次需要该目标设备的 MAC 地址时,会重新发出 ARP 请求。
= 实验总结
== 内容总结
本次实验主要围绕ARP协议的实现展开通过编写程序完善了TCP/IP协议栈的ARP协议部分。实验内容包括ARP的初始化、无回报ARP的生成、ARP的输入处理以及ARP的超时重新请求机制。在基础任务中成功实现了ARP协议的核心功能包括ARP请求与响应的构建与解析、ARP缓存表的管理等。此外还完成了拓展任务实现了多个ARP表项的管理以及IP层的输入输出处理。
在实验过程中首先通过Wireshark抓包分析了ARP报文的结构并基于此定义了ARP报文的数据结构和相关函数。接着实现了ARP报文的发送与接收功能包括ARP请求的生成与广播、ARP响应的处理以及ARP缓存表的更新。通过定时器机制实现了ARP表项的超时重传功能确保了ARP缓存的准确性和及时性。
在完成ARP协议的基础上进一步实现了IP协议和ICMP协议。通过定义IP数据报和ICMP数据报的结构实现了IP层的输入输出功能并成功实现了ICMP的ping响应功能。实验结果表明ARP、IP和ICMP协议的功能均得到了正确实现能够有效支持网络设备之间的通信。
== 心得感悟
通过本次实验我深刻理解了ARP协议的工作原理及其在网络通信中的重要作用。ARP协议作为TCP/IP协议栈中的重要组成部分负责将IP地址解析为MAC地址是网络设备之间通信的基础。通过亲手实现ARP协议的核心功能我不仅加深了对ARP协议的理解还掌握了网络协议栈的实现方法。
在实验过程中我遇到了一些挑战例如如何正确解析ARP报文、如何管理ARP缓存表以及如何处理ARP超时重传等。通过查阅资料、分析抓包数据以及反复调试代码我逐步解决了这些问题并成功实现了ARP协议的功能。这让我认识到网络协议的实现不仅需要扎实的理论基础还需要细致的调试和问题解决能力。
此外通过实现IP和ICMP协议我进一步了解了网络层协议的工作原理。IP协议负责数据包的传输而ICMP协议则用于传递控制消息。通过实现ICMP的ping响应功能我掌握了ICMP协议的基本实现方法并理解了其在网络连通性测试中的应用。
总的来说本次实验让我对TCP/IP协议栈有了更深入的理解并提升了我的编程能力和网络协议分析能力。这些知识和技能对我今后学习更复杂的网络协议以及从事网络相关工作具有重要意义。

Binary file not shown.

After

Width:  |  Height:  |  Size: 180 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 231 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 402 KiB

View File

@ -0,0 +1,61 @@
以下是具体的验证步骤:
1. 环境准备
1. 配置 IP 地址:
* 确保你的物理机(运行你程序的主机)有一个网络接口的 IP 地址在 192.168.254.0/24 网段,例如 192.168.254.1。
* 设置一台虚拟机(如 VirtualBox 或 VMWare将其网络模式设置为“桥接模式”并桥接到你物理机上一步设置的网卡。
* 在虚拟机中,手动配置 IP 地址,使其与你的物理机在同一网段,例如 192.168.254.3。 █
2. 测试连通性: █
* 在物理机上 ping 虚拟机的 IP (ping 192.168.254.3)。 █
* 在虚拟机上 ping 物理机的 IP (ping 192.168.254.1)。 █
* 确保两者可以互相 ping 通。 █
3. 编译并准备运行: █
* 确保你的代码已经编译,并且可执行文件位于 start/xnet_tiny/build/xnet。 █
2. 验证 ARP 协议 ▀
ARP 协议负责将 IP 地址解析为 MAC 硬件地址。
1. 启动抓包: 在你的物理机上打开 Wireshark选择连接虚拟机的那个网络接口开始抓包。你可以使用过滤条件 arp 来只看 ARP 包。
2. 运行你的程序: 打开一个终端,进入 network 目录,然后运行你的可执行文件:
1 ./start/xnet_tiny/build/xnet
3. 验证无回报 ARP (Gratuitous ARP):
* 预期行为: 程序启动时,会立刻发送一个 ARP 请求来宣告自己的 IP 地址 (192.168.254.2)。
* 验证方法: 在 Wireshark 中,你应该能立刻看到一个源地址是你本机 MAC、内容为 "Who has 192.168.254.2? Tell 192.168.254.2" 的 ARP 包。
4. 验证 ARP 响应:
* 预期行为: 当其他设备请求你程序的 IP 地址时,你的程序应该回复其 MAC 地址。
* 验证方法: 在虚拟机中ping 你程序模拟的 IP 地址:
1 ping 192.168.254.2
* 在 Wireshark 中,你应该能看到:
1. 一个来自虚拟机的 ARP 请求:"Who has 192.168.254.2? Tell 192.168.254.3"。
2. 一个来自你程序的 ARP 响应:"192.168.254.2 is at [你的MAC地址]"。
* 同时,检查你程序的终端输出,看是否打印出了 "learned mac addr" 的信息,表示它学习到了虚拟机的 MAC 地址。
5. 验证 ARP 超时重传:
* 预期行为: 文档中设置的 ARP 缓存条目超时时间为 10 秒 (XARP_CFG_ENTRY_OK_TMO)。超时后,程序会重新发送 ARP 请求来确认对方是否还在。
* 验证方法: 完成上一步后,让你和虚拟机的程序都保持运行。在 Wireshark 中,你应该能观察到你的程序大约每隔 10 秒就会发送一个 ARP
请求到虚拟机的 IP (192.168.254.3)。
3. 验证 ICMP (Ping) 协议
ICMP 协议用于网络控制和诊断ping 就是基于 ICMP 的。
1. 启动抓包: 在 Wireshark 中,使用过滤条件 icmp。 ▄
2. 运行程序并 Ping: 保持你的 xnet 程序运行。在虚拟机中ping 你程序的 IP 地址: █
1 ping 192.168.254.2 █
3. 验证 ICMP 响应: █
* 预期行为: 你的程序应该能响应来自虚拟机的 ICMP Echo Request (ping 请求)。 █
* 验证方法: █
1. 在虚拟机的终端里,你应该能看到 ping 命令成功接收到回复,没有丢包。 █
2. 在 Wireshark 中,你应该能看到成对的 ICMP 包: █
* Echo (ping) request 从虚拟机 (192.168.254.3) 发往你的程序 (192.168.254.2)。
* Echo (ping) reply 从你的程序 (192.168.254.2) 回复给虚拟机 (192.168.254.3)。

View File

@ -0,0 +1,130 @@
# ARP及ICMP协议实现报告
本文档详细记录了在一个C语言网络协议栈项目中从零开始实现地址解析协议ARP和Internet控制报文协议ICMP的完整过程。项目基于一个为Windows环境设计的初始模板整个过程不仅包括了协议逻辑的实现还涉及了代码的Linux兼容性改造和整体架构的模块化重构。
## 1. 初始代码分析
项目开始于一个名为`start`的目录,其中包含一个简化的网络协议栈框架。
### 1.1. 项目结构勘探
首先,我们分析了`start`目录下的源代码,特别是`xnet_tiny/src`子目录。我们识别出以下几个核心文件:
- `xnet_tiny.h`: 定义了协议栈的基本数据结构,如以太网帧头`xether_hdr_t`和网络数据包`xnet_packet_t`
- `xnet_tiny.c`: 包含了协议栈的核心驱动逻辑,如`xnet_init()`(初始化)和`xnet_poll()`(轮询)。
- `app.c`: 项目的主入口,调用`xnet_init()``xnet_poll()`来启动和运行协议栈。
- `xnet_app/port_pcap.c`: 负责与`pcap`库交互,进行底层网络数据包的收发。
### 1.2. 关键实现点定位
`xnet_tiny.c`中,我们发现了`ethernet_in`函数,它负责处理接收到的以太网数据帧。函数内部的`switch`语句根据以太网帧头的协议类型字段来分发数据包:
```c
switch (swap_order16(hdr->protocol)) {
case XNET_PROTOCOL_ARP:
// 此处为空是ARP实现入口
break;
case XNET_PROTOCOL_IP: {
// 此处为空是IP及ICMP实现入口
break;
}
}
```
这两个`case`分支是空的这正是我们需要插入ARP和IP/ICMP处理逻辑的地方。
## 2. ARP协议实现
为了保持代码的模块化我们将ARP相关的逻辑实现在单独的文件中。
### 2.1. 创建ARP模块
我们创建了以下两个文件:
- `xarp.h`: 定义ARP协议包结构`xarp_packet_t`和ARP缓存条目`xarp_entry_t`,并声明了外部接口`xarp_init()``xarp_in()`
- `xarp.c`: 实现ARP的具体逻辑。
### 2.2. 实现ARP核心逻辑
`xarp.c`中,我们完成了以下工作:
1. **ARP缓存ARP Table**: 定义了一个静态数组`arp_table[]`作为ARP缓存用于存储IP地址到MAC地址的映射。
2. **`xarp_init()`**: 此函数在协议栈初始化时被调用负责清空ARP缓存中的所有条目。
3. **`xarp_in()`**: 这是处理ARP报文的核心。
- 当接收到一个ARP请求报文时检查其请求的目标IP地址是否为本机IP。如果是则构建一个ARP响应报文填入本机的MAC地址然后通过`ethernet_out_to()`函数发送出去。
- 无论是请求还是响应都会从报文中提取发送方的IP和MAC地址并更新到ARP缓存中`update_entry`函数)。
4. **`xarp_resolve()`**: 为了让上层协议如IP能够通过IP地址查询MAC地址我们添加了此函数。它会首先查询ARP缓存。如果找到匹配的条目则返回对应的MAC地址如果未找到则调用`send_arp_request()`广播一个ARP请求并返回`NULL`,由上层决定是否重试。
### 2.3. 集成到协议栈
我们将ARP模块集成到主协议栈中
1.`xnet_tiny.c`中包含了`xarp.h`
2.`xnet_init()`函数的末尾调用`xarp_init()`
3.`ethernet_in()``switch`语句中,为`XNET_PROTOCOL_ARP`添加了对`xarp_in(packet)`的调用。
为了让`xarp.c`能够调用`xnet_tiny.c`中的`ethernet_out_to`等函数,我们将这些函数的`static`关键字移除,并在`xnet_tiny.h`中添加了它们的声明,使其成为公共接口。
## 3. ICMP及IP层实现
与ARP类似我们为ICMP和IP创建了独立的模块。
### 3.1. 创建ICMP和IP模块
- `xicmp.h`: 定义了IP报头`xip_hdr_t`和ICMP报文结构`xicmp_packet_t`
- `xicmp.c`: 实现了`xicmp_in()`函数用于处理传入的ICMP报文。
- `xip.h` / `xip.c`: 创建了一个简单的IP输出模块核心是`xip_out()`函数用于发送IP包。
### 3.2. 实现ICMP Echo Reply
`xicmp_in()`是ICMP实现的核心其工作流程如下
1. **IP报头解析**: 首先剥离以太网头部解析IP报头。验证版本号、头部长度和头部校验和。
2. **目标IP检查**: 确认该IP包的目标地址是本机。
3. **ICMP报文处理**:
- 剥离IP头部解析ICMP报文。
- 检查ICMP类型是否为**Echo Request**Ping请求
- 如果是,则准备一个**Echo Reply**Ping应答报文。大部分数据如ID、序列号和数据负载可以直接从请求报文中复制。
- 将ICMP类型设置为`ICMP_TYPE_ECHO_REPLY`然后重新计算ICMP校验和。
4. **构建IP响应包**:
- 构建IP头部源和目的IP地址与收到的请求包相反。
- 重新计算IP头部校验和。
5. **发送响应**: 调用`xip_out()`函数将响应包发送出去。`xip_out`内部会使用`xarp_resolve`来查找下一跳的MAC地址。
### 3.3. 集成到协议栈
1.`xnet_tiny.c`中包含了`xicmp.h`
2.`ethernet_in()``switch`语句中,为`XNET_PROTOCOL_IP`添加了对`xicmp_in(packet)`的调用。
3.`xicmp.c`中,使用新创建的`xip_out()`函数来发送响应包,而不是直接调用底层的`ethernet_out_to()`,实现了更好的分层。
## 4. Linux兼容性改造与重构
原始代码是为Windows设计的为了在Linux上运行我们进行了以下关键修改
1. **修正`pcap_device.c`**:
- 该文件包含了大量`#if defined(WIN32)`的条件编译块,用于加载`npcap`动态库。
- 我们删除了所有Windows特定的代码`#pragma comment`, `GetSystemDirectory`, `MessageBox`等),只保留了`#else`分支下的标准`pcap`实现使其在Linux下能够直接编译通过。
2. **修正`port_pcap.c`**:
- 原始代码中的`my_mac_addr`数组长度为8字节这是错误的。我们将其修正为标准的6字节以太网MAC地址。
- 将硬编码的pcap设备IP地址从`192.168.254.1`修改为`192.168.254.2`与我们协议栈配置的IP保持一致。
3. **IP地址集中管理**:
- 最初本机IP地址在`xarp.c``xicmp.c`中都有硬编码定义。
- 我们将其移至`xnet_tiny.c`中定义,并在`xnet_tiny.h`中通过`extern`声明,实现了全局统一配置。
## 5. 编译与测试
完成编码后,即可进行编译测试:
1. **安装依赖**: 确保Linux系统上已安装`libpcap`的开发库(如`sudo apt install libpcap-dev`)。
2. **编译**:
- 进入`start/build`目录。
- 运行`cmake ..`来生成Makefile。
- 运行`make`进行编译。
3. **运行与测试**:
- 编译成功后,会在`build`目录下生成可执行文件`xnet.exe`
- 使用`sudo ./xnet.exe`运行需要root权限以访问网络接口
- 在另一台处于同一局域网的主机上,执行`ping 192.168.254.2`即可测试ICMP Echo功能。同时可以通过`tcpdump``Wireshark`抓包观察ARP请求和响应过程。
## 6. 总结
通过以上步骤我们成功地在一个基础网络框架上完整地实现了ARP和ICMP Echo功能。整个过程不仅加深了对网络协议底层工作原理的理解也锻炼了在现有代码基础上进行功能扩展、重构和跨平台移植的能力。最终的代码结构清晰模块化程度高易于理解和进一步扩展。

8
network/arpicmplab/start/.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PublishConfigData" remoteFilesAllowedToDisappearOnAutoupload="false">
<serverData>
<paths name="ubuntu@10.107.4.40:60602 password">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
<paths name="ubuntu@10.107.4.40:60602 password (2)">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
<paths name="ubuntu@10.107.4.40:60602 password (3)">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
<paths name="ubuntu@10.107.4.40:60602 password (4)">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
<paths name="ubuntu@10.107.4.40:60602 password (5)">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
<paths name="ubuntu@10.107.4.40:60602 password (6)">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
</serverData>
</component>
</project>

View File

@ -0,0 +1,25 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="12">
<item index="0" class="java.lang.String" itemvalue="mkl-fft" />
<item index="1" class="java.lang.String" itemvalue="pandas" />
<item index="2" class="java.lang.String" itemvalue="tqdm" />
<item index="3" class="java.lang.String" itemvalue="GitPython" />
<item index="4" class="java.lang.String" itemvalue="zipp" />
<item index="5" class="java.lang.String" itemvalue="matplotlib" />
<item index="6" class="java.lang.String" itemvalue="llvmlite" />
<item index="7" class="java.lang.String" itemvalue="mkl-random" />
<item index="8" class="java.lang.String" itemvalue="torchvision" />
<item index="9" class="java.lang.String" itemvalue="importlib-metadata" />
<item index="10" class="java.lang.String" itemvalue="mkl-service" />
<item index="11" class="java.lang.String" itemvalue="torch" />
</list>
</value>
</option>
</inspection_tool>
</profile>
</component>

7
network/arpicmplab/start/.idea/misc.xml generated Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeWorkspace" PROJECT_DIR="$PROJECT_DIR$" />
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/xnet-tiny.iml" filepath="$PROJECT_DIR$/.idea/xnet-tiny.iml" />
</modules>
</component>
</project>

6
network/arpicmplab/start/.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<module classpath="CMake" type="CPP_MODULE" version="4" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

View File

@ -0,0 +1,32 @@
<html>
<head>
<title>首页|01课堂</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
.welcome {
font-size: 20px;
color: red;
}
</style>
</head>
<body>
<p class="welcome"> 注意如果网页加载很慢请将XTCP_CFG_RTX_BUF_SIZE改大比如2048</p>
<p class="welcome"> 此外如果网页加载中间出现问题属于正常现像不要意外。因本工程tcp处理很简单bug肯定很多。</p>
<p class="welcome"> 恭喜您的Web服务器成功运行。太棒了</p>
<div>
<p>您还可以点击以下链接进行测试.</p>
<ul>
<li><a href="page3.html">简单的文本</a></li>
<li><a href="1.jpg">点我欣赏妹子照片</a></li>
<li><a href="2.jpg">点我欣赏大妈照片</a></li>
<li><a href="3.jpg">点我欣赏猛男照片</a></li>
<li><a href="page1.html">多图片页面</a></li>
<li><a href="404.html">点我找不到</a></li>
<li><a href="page2.html">css + js页面</a></li>
</ul>
</div>
<div>
<h1><a href="http://01ketang.cc">别忘了访问 http://01ketang.cc获得更多学习内容噢。</a></h1>
</div>
</body>
</html>

View File

@ -0,0 +1,6 @@
var i = 0;
function button_click() {
i = i + 1;
document.getElementById("replace_p").innerHTML= i + "";
}

View File

@ -0,0 +1,18 @@
<html>
<head>
<title>师哥美女|01课堂</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p> 恭喜,欢迎欣赏师哥美女图片。</p>
<div>
<p>图片很多,慢慢欣赏.</p>
<ul>
<li><img src="4.jpg" alt="图片加载失败" /></li>
<li><img src="5.jpg" alt="图片加载失败" /></li>
<li><img src="6.jpg" alt="图片加载失败" /></li>
<li><img src="7.jpg" alt="图片加载失败" /></li>
</ul>
</div>
</body>
</html>

View File

@ -0,0 +1,17 @@
<html>
<head>
<title>带css的页面|01课堂</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<p class="info"> 有没有发现,下面的显示有点特别的?有颜色,有框框~~~</p>
<div>
<h1>这是一个显示加大加粗的红色标题</h1>
<p class="content">这是标题的内容,我们用蓝框框把他给框起来</p>
<button id="button1" type="button" onclick="button_click()">点我,统计点击次数</button>
<p id="replace_p">快点上面的按钮</p>>
</div>
</body>
</html>

View File

@ -0,0 +1,11 @@
<html>
<head>
<title>简单的文本页面|01课堂</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<h1>恭喜,你成功了</h1>
</body>
</html>

View File

@ -0,0 +1,9 @@
h1 {
color: red;
font-size: 50px;
font-style: bold;
}
.content {
border:5px solid blue;
}

View File

@ -0,0 +1,10 @@
# Makefile for cygwin gcc
# Nate Lawson <nate@rootlabs.com>
SUBDIRS = basic_dump basic_dump_ex iflist pcap_filter pktdump_ex readfile readfile_ex savedump sendpack UDPdump
all clean install uninstall: ${SUBDIRS}
for subdir in ${SUBDIRS}; do \
echo "Entering $$subdir"; \
(cd $$subdir && ${MAKE} $@) \
done;

View File

@ -0,0 +1,118 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "basic_dump", "basic_dump\basic_dump.vcxproj", "{66297062-96A0-4F0E-B147-3C8384031232}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "basic_dump_ex", "basic_dump_ex\basic_dump_ex.vcxproj", "{92849630-6B09-409C-A7AD-E91E682558B1}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "iflist", "iflist\iflist.vcxproj", "{0B27B213-4BF3-4611-B412-A2D09CDE8632}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pcap_filter", "pcap_filter\pcap_filter.vcxproj", "{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pktdump_ex", "pktdump_ex\pktdump_ex.vcxproj", "{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "readfile", "readfile\readfile.vcxproj", "{161E7606-F4CD-4A04-AB6B-5837F7818EE1}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "readfile_ex", "readfile_ex\readfile_ex.vcxproj", "{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "savedump", "savedump\savedump.vcxproj", "{1B8791CB-DD15-46BF-B0A2-879892085538}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sendpack", "sendpack\sendpack.vcxproj", "{1C376689-5F61-48E7-AE83-0DED9EE9E458}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UDPdump", "UDPdump\UDPdump.vcxproj", "{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{66297062-96A0-4F0E-B147-3C8384031232}.Debug|x64.ActiveCfg = Debug|x64
{66297062-96A0-4F0E-B147-3C8384031232}.Debug|x64.Build.0 = Debug|x64
{66297062-96A0-4F0E-B147-3C8384031232}.Debug|x86.ActiveCfg = Debug|Win32
{66297062-96A0-4F0E-B147-3C8384031232}.Debug|x86.Build.0 = Debug|Win32
{66297062-96A0-4F0E-B147-3C8384031232}.Release|x64.ActiveCfg = Release|x64
{66297062-96A0-4F0E-B147-3C8384031232}.Release|x64.Build.0 = Release|x64
{66297062-96A0-4F0E-B147-3C8384031232}.Release|x86.ActiveCfg = Release|Win32
{66297062-96A0-4F0E-B147-3C8384031232}.Release|x86.Build.0 = Release|Win32
{92849630-6B09-409C-A7AD-E91E682558B1}.Debug|x64.ActiveCfg = Debug|x64
{92849630-6B09-409C-A7AD-E91E682558B1}.Debug|x64.Build.0 = Debug|x64
{92849630-6B09-409C-A7AD-E91E682558B1}.Debug|x86.ActiveCfg = Debug|Win32
{92849630-6B09-409C-A7AD-E91E682558B1}.Debug|x86.Build.0 = Debug|Win32
{92849630-6B09-409C-A7AD-E91E682558B1}.Release|x64.ActiveCfg = Release|x64
{92849630-6B09-409C-A7AD-E91E682558B1}.Release|x64.Build.0 = Release|x64
{92849630-6B09-409C-A7AD-E91E682558B1}.Release|x86.ActiveCfg = Release|Win32
{92849630-6B09-409C-A7AD-E91E682558B1}.Release|x86.Build.0 = Release|Win32
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Debug|x64.ActiveCfg = Debug|x64
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Debug|x64.Build.0 = Debug|x64
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Debug|x86.ActiveCfg = Debug|Win32
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Debug|x86.Build.0 = Debug|Win32
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Release|x64.ActiveCfg = Release|x64
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Release|x64.Build.0 = Release|x64
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Release|x86.ActiveCfg = Release|Win32
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Release|x86.Build.0 = Release|Win32
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Debug|x64.ActiveCfg = Debug|x64
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Debug|x64.Build.0 = Debug|x64
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Debug|x86.ActiveCfg = Debug|Win32
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Debug|x86.Build.0 = Debug|Win32
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Release|x64.ActiveCfg = Release|x64
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Release|x64.Build.0 = Release|x64
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Release|x86.ActiveCfg = Release|Win32
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Release|x86.Build.0 = Release|Win32
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Debug|x64.ActiveCfg = Debug|x64
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Debug|x64.Build.0 = Debug|x64
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Debug|x86.ActiveCfg = Debug|Win32
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Debug|x86.Build.0 = Debug|Win32
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Release|x64.ActiveCfg = Release|x64
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Release|x64.Build.0 = Release|x64
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Release|x86.ActiveCfg = Release|Win32
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Release|x86.Build.0 = Release|Win32
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Debug|x64.ActiveCfg = Debug|x64
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Debug|x64.Build.0 = Debug|x64
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Debug|x86.ActiveCfg = Debug|Win32
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Debug|x86.Build.0 = Debug|Win32
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Release|x64.ActiveCfg = Release|x64
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Release|x64.Build.0 = Release|x64
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Release|x86.ActiveCfg = Release|Win32
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Release|x86.Build.0 = Release|Win32
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Debug|x64.ActiveCfg = Debug|x64
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Debug|x64.Build.0 = Debug|x64
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Debug|x86.ActiveCfg = Debug|Win32
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Debug|x86.Build.0 = Debug|Win32
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Release|x64.ActiveCfg = Release|x64
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Release|x64.Build.0 = Release|x64
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Release|x86.ActiveCfg = Release|Win32
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Release|x86.Build.0 = Release|Win32
{1B8791CB-DD15-46BF-B0A2-879892085538}.Debug|x64.ActiveCfg = Debug|x64
{1B8791CB-DD15-46BF-B0A2-879892085538}.Debug|x64.Build.0 = Debug|x64
{1B8791CB-DD15-46BF-B0A2-879892085538}.Debug|x86.ActiveCfg = Debug|Win32
{1B8791CB-DD15-46BF-B0A2-879892085538}.Debug|x86.Build.0 = Debug|Win32
{1B8791CB-DD15-46BF-B0A2-879892085538}.Release|x64.ActiveCfg = Release|x64
{1B8791CB-DD15-46BF-B0A2-879892085538}.Release|x64.Build.0 = Release|x64
{1B8791CB-DD15-46BF-B0A2-879892085538}.Release|x86.ActiveCfg = Release|Win32
{1B8791CB-DD15-46BF-B0A2-879892085538}.Release|x86.Build.0 = Release|Win32
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Debug|x64.ActiveCfg = Debug|x64
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Debug|x64.Build.0 = Debug|x64
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Debug|x86.ActiveCfg = Debug|Win32
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Debug|x86.Build.0 = Debug|Win32
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Release|x64.ActiveCfg = Release|x64
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Release|x64.Build.0 = Release|x64
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Release|x86.ActiveCfg = Release|Win32
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Release|x86.Build.0 = Release|Win32
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Debug|x64.ActiveCfg = Debug|x64
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Debug|x64.Build.0 = Debug|x64
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Debug|x86.ActiveCfg = Debug|Win32
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Debug|x86.Build.0 = Debug|Win32
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Release|x64.ActiveCfg = Release|x64
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Release|x64.Build.0 = Release|x64
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Release|x86.ActiveCfg = Release|Win32
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,17 @@
# Makefile for cygwin gcc
# Loris Degioanni
PCAP_PATH = ../../lib
CFLAGS = -g -O -mno-cygwin -I ../../include
OBJS = udpdump.o
LIBS = -L ${PCAP_PATH} -lwpcap -lwsock32
all: ${OBJS}
${CC} ${CFLAGS} -o udpdump.exe ${OBJS} ${LIBS}
clean:
rm -f ${OBJS} udpdump.exe
.c.o:
${CC} ${CFLAGS} -c -o $*.o $<

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="udpdump.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,271 @@
/*
* Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
* Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino, CACE Technologies
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifdef _MSC_VER
/*
* we do not want the warnings about the old deprecated and unsecure CRT functions
* since these examples can be compiled under *nix as well
*/
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <pcap.h>
#ifdef WIN32
#include <tchar.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
#endif
/* 4 bytes IP address */
typedef struct ip_address
{
u_char byte1;
u_char byte2;
u_char byte3;
u_char byte4;
}ip_address;
/* IPv4 header */
typedef struct ip_header
{
u_char ver_ihl; // Version (4 bits) + Internet header length (4 bits)
u_char tos; // Type of service
u_short tlen; // Total length
u_short identification; // Identification
u_short flags_fo; // Flags (3 bits) + Fragment offset (13 bits)
u_char ttl; // Time to live
u_char proto; // Protocol
u_short crc; // Header checksum
ip_address saddr; // Source address
ip_address daddr; // Destination address
u_int op_pad; // Option + Padding
}ip_header;
/* UDP header*/
typedef struct udp_header
{
u_short sport; // Source port
u_short dport; // Destination port
u_short len; // Datagram length
u_short crc; // Checksum
}udp_header;
/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
u_int netmask;
char packet_filter[] = "ip and udp";
struct bpf_program fcode;
#ifdef WIN32
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
#endif
/* Retrieve the device list */
if(pcap_findalldevs(&alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; 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 Npcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf("%d", &inum);
/* Check if the user specified a valid adapter */
if(inum < 1 || inum > i)
{
printf("\nAdapter number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the adapter */
if ((adhandle= pcap_open_live(d->name, // name of the device
65536, // portion of the packet to capture.
// 65536 grants that the whole packet will be captured on all the MACs.
1, // promiscuous mode (nonzero means promiscuous)
1000, // read timeout
errbuf // error buffer
)) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter: %s\n", errbuf);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Check the link layer. We support only Ethernet for simplicity. */
if(pcap_datalink(adhandle) != DLT_EN10MB)
{
fprintf(stderr,"\nThis program works only on Ethernet networks.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
if(d->addresses != NULL)
/* Retrieve the mask of the first address of the interface */
netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
else
/* If the interface is without addresses we suppose to be in a C class network */
netmask=0xffffff;
//compile the filter
if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0 )
{
fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
//set the filter
if (pcap_setfilter(adhandle, &fcode)<0)
{
fprintf(stderr,"\nError setting the filter.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
printf("\nlistening on %s...\n", d->description);
/* At this point, we don't need any more the device list. Free it */
pcap_freealldevs(alldevs);
/* start the capture */
pcap_loop(adhandle, 0, packet_handler, NULL);
return 0;
}
/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
struct tm *ltime;
char timestr[16];
ip_header *ih;
udp_header *uh;
u_int ip_len;
u_short sport,dport;
time_t local_tv_sec;
/*
* unused parameter
*/
(VOID)(param);
/* convert the timestamp to readable format */
local_tv_sec = header->ts.tv_sec;
ltime=localtime(&local_tv_sec);
strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);
/* print timestamp and length of the packet */
printf("%s.%.6d len:%d ", timestr, header->ts.tv_usec, header->len);
/* retireve the position of the ip header */
ih = (ip_header *) (pkt_data +
14); //length of ethernet header
/* retireve the position of the udp header */
ip_len = (ih->ver_ihl & 0xf) * 4;
uh = (udp_header *) ((u_char*)ih + ip_len);
/* convert from network byte order to host byte order */
sport = ntohs( uh->sport );
dport = ntohs( uh->dport );
/* print ip addresses and udp ports */
printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d\n",
ih->saddr.byte1,
ih->saddr.byte2,
ih->saddr.byte3,
ih->saddr.byte4,
sport,
ih->daddr.byte1,
ih->daddr.byte2,
ih->daddr.byte3,
ih->daddr.byte4,
dport);
}

View File

@ -0,0 +1,17 @@
# Makefile for cygwin gcc
# Nate Lawson <nate@rootlabs.com>
PCAP_PATH = ../../lib
CFLAGS = -g -O -mno-cygwin -I ../../include
OBJS = basic_dump.o
LIBS = -L ${PCAP_PATH} -lwpcap
all: ${OBJS}
${CC} ${CFLAGS} -o basic_dump.exe ${OBJS} ${LIBS}
clean:
rm -f ${OBJS} basic_dump.exe
.c.o:
${CC} ${CFLAGS} -c -o $*.o $<

View File

@ -0,0 +1,138 @@
#ifdef _MSC_VER
/*
* we do not want the warnings about the old deprecated and unsecure CRT functions
* since these examples can be compiled under *nix as well
*/
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <pcap.h>
#include <stdio.h>
#ifdef WIN32
#include <tchar.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
#endif
/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
#ifdef WIN32
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
#endif
/* Retrieve the device list */
if(pcap_findalldevs(&alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; 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 Npcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the device */
/* Open the adapter */
if ((adhandle= pcap_open_live(d->name, // name of the device
65536, // portion of the packet to capture.
// 65536 grants that the whole packet will be captured on all the MACs.
1, // promiscuous mode (nonzero means promiscuous)
1000, // read timeout
errbuf // error buffer
)) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->name);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
printf("\nlistening on %s...\n", d->description);
/* At this point, we don't need any more the device list. Free it */
pcap_freealldevs(alldevs);
/* start the capture */
pcap_loop(adhandle, 0, packet_handler, NULL);
pcap_close(adhandle);
return 0;
}
/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
struct tm *ltime;
char timestr[16];
time_t local_tv_sec;
/*
* unused parameters
*/
(VOID)(param);
(VOID)(pkt_data);
/* convert the timestamp to readable format */
local_tv_sec = header->ts.tv_sec;
ltime=localtime(&local_tv_sec);
strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);
printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
}

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{66297062-96A0-4F0E-B147-3C8384031232}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="basic_dump.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,17 @@
# Makefile for cygwin gcc
# Nate Lawson <nate@rootlabs.com>
PCAP_PATH = ../../lib
CFLAGS = -g -O -mno-cygwin -I ../../include
OBJS = basic_dump_ex.o
LIBS = -L ${PCAP_PATH} -lwpcap
all: ${OBJS}
${CC} ${CFLAGS} -o basic_dump_ex.exe ${OBJS} ${LIBS}
clean:
rm -f ${OBJS} basic_dump_ex.exe
.c.o:
${CC} ${CFLAGS} -c -o $*.o $<

View File

@ -0,0 +1,134 @@
#ifdef _MSC_VER
/*
* we do not want the warnings about the old deprecated and unsecure CRT functions
* since these examples can be compiled under *nix as well
*/
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <pcap.h>
#include <stdio.h>
#ifdef WIN32
#include <tchar.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
#endif
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
int res;
char errbuf[PCAP_ERRBUF_SIZE];
struct tm *ltime;
char timestr[16];
struct pcap_pkthdr *header;
const u_char *pkt_data;
time_t local_tv_sec;
#ifdef WIN32
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
#endif
/* Retrieve the device list */
if(pcap_findalldevs(&alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
return -1;
}
/* Print the list */
for(d=alldevs; 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 Npcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the adapter */
if ((adhandle= pcap_open_live(d->name, // name of the device
65536, // portion of the packet to capture.
// 65536 grants that the whole packet will be captured on all the MACs.
1, // promiscuous mode (nonzero means promiscuous)
1000, // read timeout
errbuf // error buffer
)) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->name);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
printf("\nlistening on %s...\n", d->description);
/* At this point, we don't need any more the device list. Free it */
pcap_freealldevs(alldevs);
/* Retrieve the packets */
while((res = pcap_next_ex( adhandle, &header, &pkt_data)) >= 0){
if(res == 0)
/* Timeout elapsed */
continue;
/* convert the timestamp to readable format */
local_tv_sec = header->ts.tv_sec;
ltime=localtime(&local_tv_sec);
strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);
printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
}
if(res == -1){
printf("Error reading the packets: %s\n", pcap_geterr(adhandle));
return -1;
}
pcap_close(adhandle);
return 0;
}

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{92849630-6B09-409C-A7AD-E91E682558B1}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="basic_dump_ex.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,17 @@
# Makefile for cygwin gcc
# Nate Lawson <nate@rootlabs.com>
PCAP_PATH = ../../lib
CFLAGS = -g -O -mno-cygwin -I ../../include
OBJS = iflist.o
LIBS = -L ${PCAP_PATH} -lwpcap
all: ${OBJS}
${CC} ${CFLAGS} -o iflist.exe ${OBJS} ${LIBS}
clean:
rm -f ${OBJS} iflist.exe
.c.o:
${CC} ${CFLAGS} -c -o $*.o $<

View File

@ -0,0 +1,202 @@
/*
* Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
* Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino, CACE Technologies
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifdef _MSC_VER
/*
* we do not want the warnings about the old deprecated and unsecure CRT functions
* since these examples can be compiled under *nix as well
*/
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <pcap.h>
#include <stdio.h>
#ifndef WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#else
#include <winsock.h>
#endif
#ifdef WIN32
#include <tchar.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
#endif
// Function prototypes
void ifprint(pcap_if_t *d);
char *iptos(u_long in);
char* ip6tos(struct sockaddr *sockaddr, char *address, int addrlen);
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
char errbuf[PCAP_ERRBUF_SIZE+1];
#ifdef WIN32
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
#endif
/* Retrieve the device list */
if(pcap_findalldevs(&alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Scan the list printing every entry */
for(d=alldevs;d;d=d->next)
{
ifprint(d);
}
/* Free the device list */
pcap_freealldevs(alldevs);
return 0;
}
/* Print all the available information on the given interface */
void ifprint(pcap_if_t *d)
{
pcap_addr_t *a;
char ip6str[128];
/* Name */
printf("%s\n",d->name);
/* Description */
if (d->description)
printf("\tDescription: %s\n",d->description);
/* Loopback Address*/
printf("\tLoopback: %s\n",(d->flags & PCAP_IF_LOOPBACK)?"yes":"no");
/* IP addresses */
for(a=d->addresses;a;a=a->next) {
printf("\tAddress Family: #%d\n",a->addr->sa_family);
switch(a->addr->sa_family)
{
case AF_INET:
printf("\tAddress Family Name: AF_INET\n");
if (a->addr)
printf("\tAddress: %s\n",iptos(((struct sockaddr_in *)a->addr)->sin_addr.s_addr));
if (a->netmask)
printf("\tNetmask: %s\n",iptos(((struct sockaddr_in *)a->netmask)->sin_addr.s_addr));
if (a->broadaddr)
printf("\tBroadcast Address: %s\n",iptos(((struct sockaddr_in *)a->broadaddr)->sin_addr.s_addr));
if (a->dstaddr)
printf("\tDestination Address: %s\n",iptos(((struct sockaddr_in *)a->dstaddr)->sin_addr.s_addr));
break;
case AF_INET6:
printf("\tAddress Family Name: AF_INET6\n");
#ifndef __MINGW32__ /* Cygnus doesn't have IPv6 */
if (a->addr)
printf("\tAddress: %s\n", ip6tos(a->addr, ip6str, sizeof(ip6str)));
#endif
break;
default:
printf("\tAddress Family Name: Unknown\n");
break;
}
}
printf("\n");
}
/* From tcptraceroute, convert a numeric IP address to a string */
#define IPTOSBUFFERS 12
char *iptos(u_long in)
{
static char output[IPTOSBUFFERS][3*4+3+1];
static short which;
u_char *p;
p = (u_char *)&in;
which = (which + 1 == IPTOSBUFFERS ? 0 : which + 1);
sprintf(output[which], "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
return output[which];
}
#ifndef __MINGW32__ /* Cygnus doesn't have IPv6 */
char* ip6tos(struct sockaddr *sockaddr, char *address, int addrlen)
{
socklen_t sockaddrlen;
#ifdef WIN32
sockaddrlen = sizeof(struct sockaddr_in6);
#else
sockaddrlen = sizeof(struct sockaddr_storage);
#endif
if(getnameinfo(sockaddr,
sockaddrlen,
address,
addrlen,
NULL,
0,
NI_NUMERICHOST) != 0) address = NULL;
return address;
}
#endif /* __MINGW32__ */

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{0B27B213-4BF3-4611-B412-A2D09CDE8632}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="iflist.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,17 @@
# Makefile for cygwin gcc
# Nate Lawson <nate@rootlabs.com>
PCAP_PATH = ../../lib
CFLAGS = -g -O -mno-cygwin -I ../../include
OBJS = pcap_filter.o
LIBS = -L ${PCAP_PATH} -lwpcap
all: ${OBJS}
${CC} ${CFLAGS} -o pf.exe ${OBJS} ${LIBS}
clean:
rm -f ${OBJS} pf.exe
.c.o:
${CC} ${CFLAGS} -c -o $*.o $<

View File

@ -0,0 +1,9 @@
CC = gcc
INCLDIR = -I /usr/src/sys
LIBS = -lpcap
pktdump: pcap_filter.o
$(CC) $(INCLDIR) pcap_filter.o $(LIBS) -o pf
rm *.o

View File

@ -0,0 +1,208 @@
/*
* Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
* Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino, CACE Technologies
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <pcap.h>
#define MAX_PRINT 80
#define MAX_LINE 16
#ifdef WIN32
#include <tchar.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
#endif
void usage();
int main(int argc, char **argv)
{
pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
char *source = NULL;
char *ofilename = NULL;
char *filter = NULL;
int i;
pcap_dumper_t *dumpfile;
struct bpf_program fcode;
bpf_u_int32 NetMask;
int res;
struct pcap_pkthdr *header;
const u_char *pkt_data;
#ifdef WIN32
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
#endif
if (argc == 1)
{
usage();
return -1;
}
/* Parse parameters */
for(i=1;i < argc; i+= 2)
{
switch (argv[i] [1])
{
case 's':
{
source=argv[i+1];
};
break;
case 'o':
{
ofilename=argv[i+1];
};
break;
case 'f':
{
filter=argv[i+1];
};
break;
}
}
// open a capture from the network
if (source != NULL)
{
if ((fp = pcap_open_live(source, // name of the device
65536, // portion of the packet to capture.
// 65536 grants that the whole packet will be captured on all the MACs.
1, // promiscuous mode (nonzero means promiscuous)
1000, // read timeout
errbuf // error buffer
)) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter.\n");
return -2;
}
}
else usage();
if (filter != NULL)
{
// We should loop through the adapters returned by the pcap_findalldevs_ex()
// in order to locate the correct one.
//
// Let's do things simpler: we suppose to be in a C class network ;-)
NetMask=0xffffff;
//compile the filter
if(pcap_compile(fp, &fcode, filter, 1, NetMask) < 0)
{
fprintf(stderr,"\nError compiling filter: wrong syntax.\n");
pcap_close(fp);
return -3;
}
//set the filter
if(pcap_setfilter(fp, &fcode)<0)
{
fprintf(stderr,"\nError setting the filter\n");
pcap_close(fp);
return -4;
}
}
//open the dump file
if (ofilename != NULL)
{
dumpfile= pcap_dump_open(fp, ofilename);
if (dumpfile == NULL)
{
fprintf(stderr,"\nError opening output file\n");
pcap_close(fp);
return -5;
}
}
else usage();
//start the capture
while((res = pcap_next_ex( fp, &header, &pkt_data)) >= 0)
{
if(res == 0)
/* Timeout elapsed */
continue;
//save the packet on the dump file
pcap_dump((unsigned char *) dumpfile, header, pkt_data);
}
pcap_close(fp);
pcap_dump_close(dumpfile);
return 0;
}
void usage()
{
printf("\npf - Generic Packet Filter.\n");
printf("\nUsage:\npf -s source -o output_file_name [-f filter_string]\n\n");
exit(0);
}

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="pcap_filter.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,14 @@
PCAP_PATH = ../../lib
CFLAGS = -g -O -mno-cygwin -I ../../include
OBJS = pktdump_ex.o
LIBS = -L ${PCAP_PATH} -lwpcap
all: ${OBJS}
${CC} ${CFLAGS} -o pktdump_ex.exe ${OBJS} ${LIBS}
clean:
rm -f ${OBJS} pktdump_ex.exe
.c.o:
${CC} ${CFLAGS} -c -o $*.o $<

View File

@ -0,0 +1,195 @@
/*
* Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
* Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino, CACE Technologies
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifdef _MSC_VER
/*
* we do not want the warnings about the old deprecated and unsecure CRT functions
* since these examples can be compiled under *nix as well
*/
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdlib.h>
#include <stdio.h>
#include <pcap.h>
#define LINE_LEN 16
#ifdef WIN32
#include <tchar.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
#endif
int main(int argc, char **argv)
{
pcap_if_t *alldevs, *d;
pcap_t *fp;
u_int inum, i=0;
char errbuf[PCAP_ERRBUF_SIZE];
int res;
struct pcap_pkthdr *header;
const u_char *pkt_data;
#ifdef WIN32
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
#endif
printf("pktdump_ex: prints the packets of the network using Npcap.\n");
printf(" Usage: pktdump_ex [-s source]\n\n"
" Examples:\n"
" pktdump_ex -s file.acp\n"
" pktdump_ex -s \\Device\\NPF_{C8736017-F3C3-4373-94AC-9A34B7DAD998}\n\n");
if(argc < 3)
{
printf("\nNo adapter selected: printing the device list:\n");
/* The user didn't provide a packet source: Retrieve the local device list */
if(pcap_findalldevs(&alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs_ex: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; d; d=d->next)
{
printf("%d. %s\n ", ++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 Npcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf("%d", &inum);
if (inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for (d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the adapter */
if ((fp = pcap_open_live(d->name, // name of the device
65536, // portion of the packet to capture.
// 65536 grants that the whole packet will be captured on all the MACs.
1, // promiscuous mode (nonzero means promiscuous)
1000, // read timeout
errbuf // error buffer
)) == NULL)
{
fprintf(stderr,"\nError opening adapter\n");
return -1;
}
}
else
{
/* Do not check for the switch type ('-s') */
if ((fp = pcap_open_live(argv[2], // name of the device
65536, // portion of the packet to capture.
// 65536 grants that the whole packet will be captured on all the MACs.
1, // promiscuous mode (nonzero means promiscuous)
1000, // read timeout
errbuf // error buffer
)) == NULL)
{
fprintf(stderr,"\nError opening adapter\n");
return -1;
}
}
/* Read the packets */
while((res = pcap_next_ex( fp, &header, &pkt_data)) >= 0)
{
if(res == 0)
/* Timeout elapsed */
continue;
/* print pkt timestamp and pkt len */
printf("%ld:%ld (%ld)\n", header->ts.tv_sec, header->ts.tv_usec, header->len);
/* Print the packet */
for (i=1; (i < header->caplen + 1 ) ; i++)
{
printf("%.2x ", pkt_data[i-1]);
if ( (i % LINE_LEN) == 0) printf("\n");
}
printf("\n\n");
}
if(res == -1)
{
printf("Error reading the packets: %s\n", pcap_geterr(fp));
return -1;
}
pcap_close(fp);
return 0;
}

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="pktdump_ex.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,17 @@
# Makefile for cygwin gcc
# Nate Lawson <nate@rootlabs.com>
PCAP_PATH = ../../lib
CFLAGS = -g -O -mno-cygwin -I ../../include
OBJS = readfile.o
LIBS = -L ${PCAP_PATH} -lwpcap
all: ${OBJS}
${CC} ${CFLAGS} -o readfile.exe ${OBJS} ${LIBS}
clean:
rm -f ${OBJS} readfile.exe
.c.o:
${CC} ${CFLAGS} -c -o $*.o $<

View File

@ -0,0 +1,90 @@
#include <stdio.h>
#include <pcap.h>
#define LINE_LEN 16
#ifdef WIN32
#include <tchar.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
#endif
void dispatcher_handler(u_char *, const struct pcap_pkthdr *, const u_char *);
int main(int argc, char **argv)
{
pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
#ifdef WIN32
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
#endif
if(argc != 2)
{
printf("usage: %s filename", argv[0]);
return -1;
}
/* Open the capture file */
if ((fp = pcap_open_offline(argv[1], // name of the device
errbuf // error buffer
)) == NULL)
{
fprintf(stderr,"\nUnable to open the file %s.\n", argv[1]);
return -1;
}
/* read and dispatch packets until EOF is reached */
pcap_loop(fp, 0, dispatcher_handler, NULL);
pcap_close(fp);
return 0;
}
void dispatcher_handler(u_char *temp1,
const struct pcap_pkthdr *header,
const u_char *pkt_data)
{
u_int i=0;
/*
* unused variable
*/
(VOID*)temp1;
/* print pkt timestamp and pkt len */
printf("%ld:%ld (%ld)\n", header->ts.tv_sec, header->ts.tv_usec, header->len);
/* Print the packet */
for (i=1; (i < header->caplen + 1 ) ; i++)
{
printf("%.2x ", pkt_data[i-1]);
if ( (i % LINE_LEN) == 0) printf("\n");
}
printf("\n\n");
}

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{161E7606-F4CD-4A04-AB6B-5837F7818EE1}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="readfile.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,17 @@
# Makefile for cygwin gcc
# Nate Lawson <nate@rootlabs.com>
PCAP_PATH = ../../lib
CFLAGS = -g -O -mno-cygwin -I ../../include
OBJS = readfile_ex.o
LIBS = -L ${PCAP_PATH} -lwpcap
all: ${OBJS}
${CC} ${CFLAGS} -o readfile_ex.exe ${OBJS} ${LIBS}
clean:
rm -f ${OBJS} readfile_ex.exe
.c.o:
${CC} ${CFLAGS} -c -o $*.o $<

View File

@ -0,0 +1,85 @@
#include <stdio.h>
#include <pcap.h>
#define LINE_LEN 16
#ifdef WIN32
#include <tchar.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
#endif
int main(int argc, char **argv)
{
pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
struct pcap_pkthdr *header;
const u_char *pkt_data;
u_int i=0;
int res;
#ifdef WIN32
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
#endif
if(argc != 2)
{
printf("usage: %s filename", argv[0]);
return -1;
}
/* Open the capture file */
if ((fp = pcap_open_offline(argv[1], // name of the device
errbuf // error buffer
)) == NULL)
{
fprintf(stderr,"\nUnable to open the file %s.\n", argv[1]);
return -1;
}
/* Retrieve the packets from the file */
while((res = pcap_next_ex(fp, &header, &pkt_data)) >= 0)
{
/* print pkt timestamp and pkt len */
printf("%ld:%ld (%ld)\n", header->ts.tv_sec, header->ts.tv_usec, header->len);
/* Print the packet */
for (i=1; (i < header->caplen + 1 ) ; i++)
{
printf("%.2x ", pkt_data[i-1]);
if ( (i % LINE_LEN) == 0) printf("\n");
}
printf("\n\n");
}
if (res == -1)
{
printf("Error reading the packets: %s\n", pcap_geterr(fp));
}
pcap_close(fp);
return 0;
}

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="readfile_ex.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,17 @@
# Makefile for cygwin gcc
# Nate Lawson <nate@rootlabs.com>
PCAP_PATH = ../../lib
CFLAGS = -g -O -mno-cygwin -I ../../include
OBJS = savedump.o
LIBS = -L ${PCAP_PATH} -lwpcap
all: ${OBJS}
${CC} ${CFLAGS} -o savedump.exe ${OBJS} ${LIBS}
clean:
rm -f ${OBJS} savedump.exe
.c.o:
${CC} ${CFLAGS} -c -o $*.o $<

View File

@ -0,0 +1,140 @@
#ifdef _MSC_VER
/*
* we do not want the warnings about the old deprecated and unsecure CRT functions
* since these examples can be compiled under *nix as well
*/
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <pcap.h>
#ifdef WIN32
#include <tchar.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
#endif
/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
int main(int argc, char **argv)
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
pcap_dumper_t *dumpfile;
#ifdef WIN32
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
#endif
/* Check command line */
if(argc != 2)
{
printf("usage: %s filename", argv[0]);
return -1;
}
/* Retrieve the device list on the local machine */
if (pcap_findalldevs(&alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; 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 Npcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the adapter */
if ((adhandle= pcap_open_live(d->name, // name of the device
65536, // portion of the packet to capture.
// 65536 grants that the whole packet will be captured on all the MACs.
1, // promiscuous mode (nonzero means promiscuous)
1000, // read timeout
errbuf // error buffer
)) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->name);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Open the dump file */
dumpfile = pcap_dump_open(adhandle, argv[1]);
if(dumpfile==NULL)
{
fprintf(stderr,"\nError opening output file\n");
return -1;
}
printf("\nlistening on %s... Press Ctrl+C to stop...\n", d->description);
/* At this point, we no longer need the device list. Free it */
pcap_freealldevs(alldevs);
/* start the capture */
pcap_loop(adhandle, 0, packet_handler, (unsigned char *)dumpfile);
pcap_close(adhandle);
return 0;
}
/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(u_char *dumpfile, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
/* save the packet on the dump file */
pcap_dump(dumpfile, header, pkt_data);
}

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{1B8791CB-DD15-46BF-B0A2-879892085538}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="savedump.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,17 @@
# Makefile for cygwin gcc
# Nate Lawson <nate@rootlabs.com>
PCAP_PATH = ../../lib
CFLAGS = -g -O -mno-cygwin -I ../../include
OBJS = sendpack.o
LIBS = -L ${PCAP_PATH} -lwpcap
all: ${OBJS}
${CC} ${CFLAGS} -o sendpack.exe ${OBJS} ${LIBS}
clean:
rm -f ${OBJS} sendpack.exe
.c.o:
${CC} ${CFLAGS} -c -o $*.o $<

View File

@ -0,0 +1,97 @@
#include <stdlib.h>
#include <stdio.h>
#include <pcap.h>
#ifdef WIN32
#include <tchar.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
#endif
int main(int argc, char **argv)
{
pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
u_char packet[100];
int i;
#ifdef WIN32
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
#endif
/* Check the validity of the command line */
if (argc != 2)
{
printf("usage: %s interface", argv[0]);
return 1;
}
/* Open the adapter */
if ((fp = pcap_open_live(argv[1], // name of the device
65536, // portion of the packet to capture. It doesn't matter in this case
1, // promiscuous mode (nonzero means promiscuous)
1000, // read timeout
errbuf // error buffer
)) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", argv[1]);
return 2;
}
/* Supposing to be on ethernet, set mac destination to 1:1:1:1:1:1 */
packet[0]=1;
packet[1]=1;
packet[2]=1;
packet[3]=1;
packet[4]=1;
packet[5]=1;
/* set mac source to 2:2:2:2:2:2 */
packet[6]=2;
packet[7]=2;
packet[8]=2;
packet[9]=2;
packet[10]=2;
packet[11]=2;
/* Fill the rest of the packet */
for(i=12;i<100;i++)
{
packet[i]= (u_char)i;
}
/* Send down the packet */
if (pcap_sendpacket(fp, // Adapter
packet, // buffer with the packet
100 // size
) != 0)
{
fprintf(stderr,"\nError sending the packet: %s\n", pcap_geterr(fp));
return 3;
}
pcap_close(fp);
return 0;
}

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{1C376689-5F61-48E7-AE83-0DED9EE9E458}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="sendpack.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,198 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "iflist", "iflist\iflist.vcxproj", "{0B27B213-4BF3-4611-B412-A2D09CDE8632}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sendcap", "sendcap\sendcap.vcxproj", "{D6B93A03-446A-4B13-87B8-9AA752A5CC8C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "GetMacAddress", "PacketDriver\GetMacAddress\GetMacAddress.vcxproj", "{1ED069D6-3B12-4175-A97D-7FFEBEA26628}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestPacketCapture", "PacketDriver\TestPacketCapture\TestPacketCapture.vcxproj", "{79942922-E02C-486D-9EE3-A13C0876C4C2}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestPacketSend", "PacketDriver\TestPacketSend\TestPacketSend.vcxproj", "{1E3BED58-2F2C-463A-B9FD-9A55235C6840}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pcap_filter", "pcap_filter\pcap_filter.vcxproj", "{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pcap_fopen", "pcap_fopen\pcap_fopen.vcxproj", "{DD317CB5-6337-498F-A560-553B5558E133}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pktdump_ex", "pktdump_ex\pktdump_ex.vcxproj", "{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "smp_1", "smp_1\smp_1.vcxproj", "{21F49E7F-6C58-4DA5-ABE5-A9DFB6165C83}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tcptop", "tcptop\tcptop.vcxproj", "{B671D5DF-3A80-4A21-BC01-79E3FB73D372}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UDPdump", "UDPdump\UDPdump.vcxproj", "{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UserBridge", "UserLevelBridge\UserBridge.vcxproj", "{BB73BFD4-454F-42C8-AFE6-FA890A8BD8FC}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "basic_dump", "misc\basic_dump.vcxproj", "{66297062-96A0-4F0E-B147-3C8384031232}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "basic_dump_ex", "misc\basic_dump_ex.vcxproj", "{92849630-6B09-409C-A7AD-E91E682558B1}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "readfile", "misc\readfile.vcxproj", "{161E7606-F4CD-4A04-AB6B-5837F7818EE1}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "readfile_ex", "misc\readfile_ex.vcxproj", "{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "savedump", "misc\savedump.vcxproj", "{1B8791CB-DD15-46BF-B0A2-879892085538}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sendpack", "misc\sendpack.vcxproj", "{1C376689-5F61-48E7-AE83-0DED9EE9E458}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Debug|x64.ActiveCfg = Debug|x64
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Debug|x64.Build.0 = Debug|x64
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Debug|x86.ActiveCfg = Debug|Win32
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Debug|x86.Build.0 = Debug|Win32
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Release|x64.ActiveCfg = Release|x64
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Release|x64.Build.0 = Release|x64
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Release|x86.ActiveCfg = Release|Win32
{0B27B213-4BF3-4611-B412-A2D09CDE8632}.Release|x86.Build.0 = Release|Win32
{D6B93A03-446A-4B13-87B8-9AA752A5CC8C}.Debug|x64.ActiveCfg = Debug|x64
{D6B93A03-446A-4B13-87B8-9AA752A5CC8C}.Debug|x64.Build.0 = Debug|x64
{D6B93A03-446A-4B13-87B8-9AA752A5CC8C}.Debug|x86.ActiveCfg = Debug|Win32
{D6B93A03-446A-4B13-87B8-9AA752A5CC8C}.Debug|x86.Build.0 = Debug|Win32
{D6B93A03-446A-4B13-87B8-9AA752A5CC8C}.Release|x64.ActiveCfg = Release|x64
{D6B93A03-446A-4B13-87B8-9AA752A5CC8C}.Release|x64.Build.0 = Release|x64
{D6B93A03-446A-4B13-87B8-9AA752A5CC8C}.Release|x86.ActiveCfg = Release|Win32
{D6B93A03-446A-4B13-87B8-9AA752A5CC8C}.Release|x86.Build.0 = Release|Win32
{1ED069D6-3B12-4175-A97D-7FFEBEA26628}.Debug|x64.ActiveCfg = Debug|x64
{1ED069D6-3B12-4175-A97D-7FFEBEA26628}.Debug|x64.Build.0 = Debug|x64
{1ED069D6-3B12-4175-A97D-7FFEBEA26628}.Debug|x86.ActiveCfg = Debug|Win32
{1ED069D6-3B12-4175-A97D-7FFEBEA26628}.Debug|x86.Build.0 = Debug|Win32
{1ED069D6-3B12-4175-A97D-7FFEBEA26628}.Release|x64.ActiveCfg = Release|x64
{1ED069D6-3B12-4175-A97D-7FFEBEA26628}.Release|x64.Build.0 = Release|x64
{1ED069D6-3B12-4175-A97D-7FFEBEA26628}.Release|x86.ActiveCfg = Release|Win32
{1ED069D6-3B12-4175-A97D-7FFEBEA26628}.Release|x86.Build.0 = Release|Win32
{79942922-E02C-486D-9EE3-A13C0876C4C2}.Debug|x64.ActiveCfg = Debug|x64
{79942922-E02C-486D-9EE3-A13C0876C4C2}.Debug|x64.Build.0 = Debug|x64
{79942922-E02C-486D-9EE3-A13C0876C4C2}.Debug|x86.ActiveCfg = Debug|Win32
{79942922-E02C-486D-9EE3-A13C0876C4C2}.Debug|x86.Build.0 = Debug|Win32
{79942922-E02C-486D-9EE3-A13C0876C4C2}.Release|x64.ActiveCfg = Release|x64
{79942922-E02C-486D-9EE3-A13C0876C4C2}.Release|x64.Build.0 = Release|x64
{79942922-E02C-486D-9EE3-A13C0876C4C2}.Release|x86.ActiveCfg = Release|Win32
{79942922-E02C-486D-9EE3-A13C0876C4C2}.Release|x86.Build.0 = Release|Win32
{1E3BED58-2F2C-463A-B9FD-9A55235C6840}.Debug|x64.ActiveCfg = Debug|x64
{1E3BED58-2F2C-463A-B9FD-9A55235C6840}.Debug|x64.Build.0 = Debug|x64
{1E3BED58-2F2C-463A-B9FD-9A55235C6840}.Debug|x86.ActiveCfg = Debug|Win32
{1E3BED58-2F2C-463A-B9FD-9A55235C6840}.Debug|x86.Build.0 = Debug|Win32
{1E3BED58-2F2C-463A-B9FD-9A55235C6840}.Release|x64.ActiveCfg = Release|x64
{1E3BED58-2F2C-463A-B9FD-9A55235C6840}.Release|x64.Build.0 = Release|x64
{1E3BED58-2F2C-463A-B9FD-9A55235C6840}.Release|x86.ActiveCfg = Release|Win32
{1E3BED58-2F2C-463A-B9FD-9A55235C6840}.Release|x86.Build.0 = Release|Win32
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Debug|x64.ActiveCfg = Debug|x64
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Debug|x64.Build.0 = Debug|x64
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Debug|x86.ActiveCfg = Debug|Win32
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Debug|x86.Build.0 = Debug|Win32
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Release|x64.ActiveCfg = Release|x64
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Release|x64.Build.0 = Release|x64
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Release|x86.ActiveCfg = Release|Win32
{B9F68F6F-22AE-47A2-A3A3-1212831AF9FF}.Release|x86.Build.0 = Release|Win32
{DD317CB5-6337-498F-A560-553B5558E133}.Debug|x64.ActiveCfg = Debug|x64
{DD317CB5-6337-498F-A560-553B5558E133}.Debug|x64.Build.0 = Debug|x64
{DD317CB5-6337-498F-A560-553B5558E133}.Debug|x86.ActiveCfg = Debug|Win32
{DD317CB5-6337-498F-A560-553B5558E133}.Debug|x86.Build.0 = Debug|Win32
{DD317CB5-6337-498F-A560-553B5558E133}.Release|x64.ActiveCfg = Release|x64
{DD317CB5-6337-498F-A560-553B5558E133}.Release|x64.Build.0 = Release|x64
{DD317CB5-6337-498F-A560-553B5558E133}.Release|x86.ActiveCfg = Release|Win32
{DD317CB5-6337-498F-A560-553B5558E133}.Release|x86.Build.0 = Release|Win32
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Debug|x64.ActiveCfg = Debug|x64
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Debug|x64.Build.0 = Debug|x64
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Debug|x86.ActiveCfg = Debug|Win32
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Debug|x86.Build.0 = Debug|Win32
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Release|x64.ActiveCfg = Release|x64
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Release|x64.Build.0 = Release|x64
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Release|x86.ActiveCfg = Release|Win32
{3D62DEB4-3536-44AE-8E4B-AD6DFF1B795E}.Release|x86.Build.0 = Release|Win32
{21F49E7F-6C58-4DA5-ABE5-A9DFB6165C83}.Debug|x64.ActiveCfg = Debug|x64
{21F49E7F-6C58-4DA5-ABE5-A9DFB6165C83}.Debug|x64.Build.0 = Debug|x64
{21F49E7F-6C58-4DA5-ABE5-A9DFB6165C83}.Debug|x86.ActiveCfg = Debug|Win32
{21F49E7F-6C58-4DA5-ABE5-A9DFB6165C83}.Debug|x86.Build.0 = Debug|Win32
{21F49E7F-6C58-4DA5-ABE5-A9DFB6165C83}.Release|x64.ActiveCfg = Release|x64
{21F49E7F-6C58-4DA5-ABE5-A9DFB6165C83}.Release|x64.Build.0 = Release|x64
{21F49E7F-6C58-4DA5-ABE5-A9DFB6165C83}.Release|x86.ActiveCfg = Release|Win32
{21F49E7F-6C58-4DA5-ABE5-A9DFB6165C83}.Release|x86.Build.0 = Release|Win32
{B671D5DF-3A80-4A21-BC01-79E3FB73D372}.Debug|x64.ActiveCfg = Debug|x64
{B671D5DF-3A80-4A21-BC01-79E3FB73D372}.Debug|x64.Build.0 = Debug|x64
{B671D5DF-3A80-4A21-BC01-79E3FB73D372}.Debug|x86.ActiveCfg = Debug|Win32
{B671D5DF-3A80-4A21-BC01-79E3FB73D372}.Debug|x86.Build.0 = Debug|Win32
{B671D5DF-3A80-4A21-BC01-79E3FB73D372}.Release|x64.ActiveCfg = Release|x64
{B671D5DF-3A80-4A21-BC01-79E3FB73D372}.Release|x64.Build.0 = Release|x64
{B671D5DF-3A80-4A21-BC01-79E3FB73D372}.Release|x86.ActiveCfg = Release|Win32
{B671D5DF-3A80-4A21-BC01-79E3FB73D372}.Release|x86.Build.0 = Release|Win32
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Debug|x64.ActiveCfg = Debug|x64
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Debug|x64.Build.0 = Debug|x64
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Debug|x86.ActiveCfg = Debug|Win32
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Debug|x86.Build.0 = Debug|Win32
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Release|x64.ActiveCfg = Release|x64
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Release|x64.Build.0 = Release|x64
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Release|x86.ActiveCfg = Release|Win32
{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}.Release|x86.Build.0 = Release|Win32
{BB73BFD4-454F-42C8-AFE6-FA890A8BD8FC}.Debug|x64.ActiveCfg = Debug|x64
{BB73BFD4-454F-42C8-AFE6-FA890A8BD8FC}.Debug|x64.Build.0 = Debug|x64
{BB73BFD4-454F-42C8-AFE6-FA890A8BD8FC}.Debug|x86.ActiveCfg = Debug|Win32
{BB73BFD4-454F-42C8-AFE6-FA890A8BD8FC}.Debug|x86.Build.0 = Debug|Win32
{BB73BFD4-454F-42C8-AFE6-FA890A8BD8FC}.Release|x64.ActiveCfg = Release|x64
{BB73BFD4-454F-42C8-AFE6-FA890A8BD8FC}.Release|x64.Build.0 = Release|x64
{BB73BFD4-454F-42C8-AFE6-FA890A8BD8FC}.Release|x86.ActiveCfg = Release|Win32
{BB73BFD4-454F-42C8-AFE6-FA890A8BD8FC}.Release|x86.Build.0 = Release|Win32
{66297062-96A0-4F0E-B147-3C8384031232}.Debug|x64.ActiveCfg = Debug|x64
{66297062-96A0-4F0E-B147-3C8384031232}.Debug|x64.Build.0 = Debug|x64
{66297062-96A0-4F0E-B147-3C8384031232}.Debug|x86.ActiveCfg = Debug|Win32
{66297062-96A0-4F0E-B147-3C8384031232}.Debug|x86.Build.0 = Debug|Win32
{66297062-96A0-4F0E-B147-3C8384031232}.Release|x64.ActiveCfg = Release|x64
{66297062-96A0-4F0E-B147-3C8384031232}.Release|x64.Build.0 = Release|x64
{66297062-96A0-4F0E-B147-3C8384031232}.Release|x86.ActiveCfg = Release|Win32
{66297062-96A0-4F0E-B147-3C8384031232}.Release|x86.Build.0 = Release|Win32
{92849630-6B09-409C-A7AD-E91E682558B1}.Debug|x64.ActiveCfg = Debug|x64
{92849630-6B09-409C-A7AD-E91E682558B1}.Debug|x64.Build.0 = Debug|x64
{92849630-6B09-409C-A7AD-E91E682558B1}.Debug|x86.ActiveCfg = Debug|Win32
{92849630-6B09-409C-A7AD-E91E682558B1}.Debug|x86.Build.0 = Debug|Win32
{92849630-6B09-409C-A7AD-E91E682558B1}.Release|x64.ActiveCfg = Release|x64
{92849630-6B09-409C-A7AD-E91E682558B1}.Release|x64.Build.0 = Release|x64
{92849630-6B09-409C-A7AD-E91E682558B1}.Release|x86.ActiveCfg = Release|Win32
{92849630-6B09-409C-A7AD-E91E682558B1}.Release|x86.Build.0 = Release|Win32
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Debug|x64.ActiveCfg = Debug|x64
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Debug|x64.Build.0 = Debug|x64
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Debug|x86.ActiveCfg = Debug|Win32
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Debug|x86.Build.0 = Debug|Win32
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Release|x64.ActiveCfg = Release|x64
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Release|x64.Build.0 = Release|x64
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Release|x86.ActiveCfg = Release|Win32
{161E7606-F4CD-4A04-AB6B-5837F7818EE1}.Release|x86.Build.0 = Release|Win32
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Debug|x64.ActiveCfg = Debug|x64
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Debug|x64.Build.0 = Debug|x64
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Debug|x86.ActiveCfg = Debug|Win32
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Debug|x86.Build.0 = Debug|Win32
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Release|x64.ActiveCfg = Release|x64
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Release|x64.Build.0 = Release|x64
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Release|x86.ActiveCfg = Release|Win32
{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}.Release|x86.Build.0 = Release|Win32
{1B8791CB-DD15-46BF-B0A2-879892085538}.Debug|x64.ActiveCfg = Debug|x64
{1B8791CB-DD15-46BF-B0A2-879892085538}.Debug|x64.Build.0 = Debug|x64
{1B8791CB-DD15-46BF-B0A2-879892085538}.Debug|x86.ActiveCfg = Debug|Win32
{1B8791CB-DD15-46BF-B0A2-879892085538}.Debug|x86.Build.0 = Debug|Win32
{1B8791CB-DD15-46BF-B0A2-879892085538}.Release|x64.ActiveCfg = Release|x64
{1B8791CB-DD15-46BF-B0A2-879892085538}.Release|x64.Build.0 = Release|x64
{1B8791CB-DD15-46BF-B0A2-879892085538}.Release|x86.ActiveCfg = Release|Win32
{1B8791CB-DD15-46BF-B0A2-879892085538}.Release|x86.Build.0 = Release|Win32
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Debug|x64.ActiveCfg = Debug|x64
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Debug|x64.Build.0 = Debug|x64
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Debug|x86.ActiveCfg = Debug|Win32
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Debug|x86.Build.0 = Debug|Win32
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Release|x64.ActiveCfg = Release|x64
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Release|x64.Build.0 = Release|x64
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Release|x86.ActiveCfg = Release|Win32
{1C376689-5F61-48E7-AE83-0DED9EE9E458}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,177 @@
/*
* Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
* Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino, CACE Technologies
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdio.h>
#include <conio.h>
#include <Packet32.h>
#include <ntddndis.h>
#define Max_Num_Adapter 10
char AdapterList[Max_Num_Adapter][1024];
#include <tchar.h>
BOOL LoadNpcapDlls()
{
TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, TEXT("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
int main()
{
LPADAPTER lpAdapter = 0;
int i;
DWORD dwErrorCode;
char AdapterName[8192];
char *temp,*temp1;
int AdapterNum=0,Open;
ULONG AdapterLength;
PPACKET_OID_DATA OidData;
BOOLEAN Status;
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
//
// Obtain the name of the adapters installed on this machine
//
printf("Packet.dll test application. Library version:%s\n", PacketGetVersion());
printf("Adapters installed:\n");
i=0;
AdapterLength = sizeof(AdapterName);
if(PacketGetAdapterNames(AdapterName,&AdapterLength)==FALSE){
printf("Unable to retrieve the list of the adapters!\n");
return -1;
}
temp=AdapterName;
temp1=AdapterName;
while ((*temp!='\0')||(*(temp-1)!='\0'))
{
if (*temp=='\0')
{
memcpy(AdapterList[i],temp1,temp-temp1);
temp1=temp+1;
i++;
}
temp++;
}
AdapterNum=i;
for (i=0;i<AdapterNum;i++)
printf("\n%d- %s\n",i+1,AdapterList[i]);
printf("\n");
do
{
printf("Select the number of the adapter to open : ");
scanf_s("%d",&Open);
if (Open>AdapterNum) printf("\nThe number must be smaller than %d",AdapterNum);
} while (Open>AdapterNum);
//
// Open the selected adapter
//
lpAdapter = PacketOpenAdapter(AdapterList[Open-1]);
if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE))
{
dwErrorCode=GetLastError();
printf("Unable to open the adapter, Error Code : %lx\n",dwErrorCode);
return -1;
}
//
// Allocate a buffer to get the MAC adress
//
OidData = malloc(6 + sizeof(PACKET_OID_DATA));
if (OidData == NULL)
{
printf("error allocating memory!\n");
PacketCloseAdapter(lpAdapter);
return -1;
}
//
// Retrieve the adapter MAC querying the NIC driver
//
OidData->Oid = OID_802_3_CURRENT_ADDRESS;
OidData->Length = 6;
ZeroMemory(OidData->Data, 6);
Status = PacketRequest(lpAdapter, FALSE, OidData);
if(Status)
{
printf("The MAC address of the adapter is %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
(OidData->Data)[0],
(OidData->Data)[1],
(OidData->Data)[2],
(OidData->Data)[3],
(OidData->Data)[4],
(OidData->Data)[5]);
}
else
{
printf("error retrieving the MAC address of the adapter!\n");
}
free(OidData);
PacketCloseAdapter(lpAdapter);
return (0);
}

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{1ED069D6-3B12-4175-A97D-7FFEBEA26628}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>Packet.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>Packet.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>Packet.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>Packet.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>Packet.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>Packet.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>Packet.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>Packet.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="GetMacAddress.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,268 @@
/*
* Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
* Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino, CACE Technologies
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdio.h>
#include <conio.h>
#include <Packet32.h>
#include <ntddndis.h>
#define Max_Num_Adapter 10
#include <tchar.h>
BOOL LoadNpcapDlls()
{
TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, TEXT("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
// Prototypes
void PrintPackets(LPPACKET lpPacket);
char AdapterList[Max_Num_Adapter][1024];
int main()
{
//define a pointer to an ADAPTER structure
LPADAPTER lpAdapter = 0;
//define a pointer to a PACKET structure
LPPACKET lpPacket;
int i;
DWORD dwErrorCode;
//ascii strings
char AdapterName[8192]; // string that contains a list of the network adapters
char *temp,*temp1;
int AdapterNum=0,Open;
ULONG AdapterLength;
char buffer[256000]; // buffer to hold the data coming from the driver
struct bpf_stat stat;
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
//
// Obtain the name of the adapters installed on this machine
//
printf("Packet.dll test application. Library version:%s\n", PacketGetVersion());
printf("Adapters installed:\n");
i=0;
AdapterLength = sizeof(AdapterName);
if(PacketGetAdapterNames(AdapterName,&AdapterLength)==FALSE){
printf("Unable to retrieve the list of the adapters!\n");
return -1;
}
temp=AdapterName;
temp1=AdapterName;
while ((*temp!='\0')||(*(temp-1)!='\0'))
{
if (*temp=='\0')
{
memcpy(AdapterList[i],temp1,temp-temp1);
temp1=temp+1;
i++;
}
temp++;
}
AdapterNum=i;
for (i=0;i<AdapterNum;i++)
printf("\n%d- %s\n",i+1,AdapterList[i]);
printf("\n");
do
{
printf("Select the number of the adapter to open : ");
scanf_s("%d",&Open);
if (Open>AdapterNum) printf("\nThe number must be smaller than %d",AdapterNum);
} while (Open>AdapterNum);
lpAdapter = PacketOpenAdapter(AdapterList[Open-1]);
if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE))
{
dwErrorCode=GetLastError();
printf("Unable to open the adapter, Error Code : %lx\n",dwErrorCode);
return -1;
}
// set the network adapter in promiscuous mode
if(PacketSetHwFilter(lpAdapter,NDIS_PACKET_TYPE_PROMISCUOUS)==FALSE){
printf("Warning: unable to set promiscuous mode!\n");
}
// set a 512K buffer in the driver
if(PacketSetBuff(lpAdapter,512000)==FALSE){
printf("Unable to set the kernel buffer!\n");
return -1;
}
// set a 1 second read timeout
if(PacketSetReadTimeout(lpAdapter,1000)==FALSE){
printf("Warning: unable to set the read tiemout!\n");
}
//allocate and initialize a packet structure that will be used to
//receive the packets.
if((lpPacket = PacketAllocatePacket())==NULL){
printf("\nError: failed to allocate the LPPACKET structure.");
return (-1);
}
PacketInitPacket(lpPacket,(char*)buffer,256000);
//main capture loop
while(!_kbhit())
{
// capture the packets
if(PacketReceivePacket(lpAdapter,lpPacket,TRUE)==FALSE){
printf("Error: PacketReceivePacket failed");
return (-1);
}
PrintPackets(lpPacket);
}
//print the capture statistics
if(PacketGetStats(lpAdapter,&stat)==FALSE){
printf("Warning: unable to get stats from the kernel!\n");
}
else
printf("\n\n%d packets received.\n%d Packets lost",stat.bs_recv,stat.bs_drop);
PacketFreePacket(lpPacket);
// close the adapter and exit
PacketCloseAdapter(lpAdapter);
return (0);
}
// this function prints the content of a block of packets received from the driver
void PrintPackets(LPPACKET lpPacket)
{
ULONG i, j, ulLines, ulen, ulBytesReceived;
char *pChar, *pLine, *base;
char *buf;
u_int off=0;
u_int tlen,tlen1;
struct bpf_hdr *hdr;
ulBytesReceived = lpPacket->ulBytesReceived;
buf = lpPacket->Buffer;
off=0;
while(off<ulBytesReceived){
if(_kbhit())return;
hdr=(struct bpf_hdr *)(buf+off);
tlen1=hdr->bh_datalen;
tlen=hdr->bh_caplen;
printf("Packet length, captured portion: %ld, %ld\n", tlen1, tlen);
off+=hdr->bh_hdrlen;
ulLines = (tlen + 15) / 16;
pChar =(char*)(buf+off);
base=pChar;
off=Packet_WORDALIGN(off+tlen);
for ( i=0; i<ulLines; i++ )
{
pLine =pChar;
printf( "%p : ", (void *)(pChar - base));
ulen=tlen;
ulen = ( ulen > 16 ) ? 16 : ulen;
tlen -= ulen;
for ( j=0; j<ulen; j++ )
printf( "%02x ", *(BYTE *)pChar++ );
if ( ulen < 16 )
printf( "%*s", (16-ulen)*3, " " );
pChar = pLine;
for ( j=0; j<ulen; j++, pChar++ )
printf( "%c", isprint( (unsigned char)*pChar ) ? *pChar : '.' );
printf( "\n" );
}
printf( "\n" );
}
}

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{79942922-E02C-486D-9EE3-A13C0876C4C2}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>Packet.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>Packet.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>Packet.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>Packet.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>Packet.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>Packet.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>Packet.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>Packet.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="TestPacketCapture.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,260 @@
/*
* Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
* Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino, CACE Technologies
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <Packet32.h>
#define Max_Num_Adapter 10
#include <tchar.h>
BOOL LoadNpcapDlls()
{
TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, TEXT("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
// Prototypes
void PrintPackets(LPPACKET lpPacket);
char AdapterList[Max_Num_Adapter][8192];
int main(int argc, char **argv)
{
char packetbuff[5000];
// define a pointer to a ADAPTER structure
LPADAPTER lpAdapter = 0;
// define a pointer to a PACKET structure
LPPACKET lpPacket;
int i,npacks,Snaplen;
DWORD dwErrorCode;
//ascii strings
char AdapterName[8192]; // string that contains a list of the network adapters
char *temp,*temp1;
int AdapterNum=0,Open;
ULONG AdapterLength;
float cpu_time;
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
printf("Traffic Generator v 0.9999\nCopyright 1999 Loris Degioanni (loris@netgroup-serv.polito.it)");
printf("\nSends a set of packets to the network using packet.dll API.\n");
if (argc == 1){
printf("\n\n Usage: TestpacketSend [-i adapter] -n npacks -s size");
printf("\n size is between 60 and 1514\n\n");
return -1;
}
AdapterName[0]=0;
//get the command line parameters
for(i=1;i<argc;i+=2){
switch (argv[i] [1])
{
case 'i':
sscanf_s(argv[i+1],"%s",AdapterName, (unsigned)_countof(AdapterName));
break;
case 'n':
sscanf_s(argv[i+1],"%d",&npacks);
break;
case 's':
sscanf_s(argv[i+1],"%d",&Snaplen);
break;
}
}
if(AdapterName[0]==0){
//
// Obtain the name of the adapters installed on this machine
//
printf("Adapters installed:\n");
i=0;
AdapterLength = sizeof(AdapterName);
if(PacketGetAdapterNames(AdapterName,&AdapterLength)==FALSE){
printf("Unable to retrieve the list of the adapters!\n");
return -1;
}
temp=AdapterName;
temp1=AdapterName;
while ((*temp!='\0')||(*(temp-1)!='\0'))
{
if (*temp=='\0')
{
memcpy(AdapterList[i],temp1,temp-temp1);
temp1=temp+1;
i++;
}
temp++;
}
AdapterNum=i;
for (i=0;i<AdapterNum;i++)
printf("\n%d- %s\n",i+1,AdapterList[i]);
printf("\n");
do
{
printf("Select the number of the adapter to open : ");scanf_s("%d",&Open);
if (Open>AdapterNum) printf("\nThe number must be smaller than %d",AdapterNum);
} while (Open>AdapterNum);
lpAdapter = PacketOpenAdapter(AdapterList[Open-1]);
if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE))
{
dwErrorCode=GetLastError();
printf("Unable to open the driver, Error Code : %lx\n",dwErrorCode);
return(-1);
}
}
else{
lpAdapter = PacketOpenAdapter(AdapterName);
if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE))
{
dwErrorCode=GetLastError();
printf("Unable to open the driver, Error Code : %lx\n",dwErrorCode);
return(-1);
}
}
if((lpPacket = PacketAllocatePacket())==NULL){
printf("\nError:failed to allocate the LPPACKET structure.");
return (-1);
}
packetbuff[0]=1;
packetbuff[1]=1;
packetbuff[2]=1;
packetbuff[3]=1;
packetbuff[4]=1;
packetbuff[5]=1;
packetbuff[6]=2;
packetbuff[7]=2;
packetbuff[8]=2;
packetbuff[9]=2;
packetbuff[10]=2;
packetbuff[11]=2;
for(i=12;i<1514;i++){
packetbuff[i]= (char)i;
}
PacketInitPacket(lpPacket,packetbuff,Snaplen);
// capture the packet
if(PacketSetNumWrites(lpAdapter,npacks)==FALSE){
printf("warning: Unable to send more than one packet in a single write!\n");
}
printf("\n\nGenerating %d packets...",npacks);
cpu_time = (float)clock ();
if(PacketSendPacket(lpAdapter,lpPacket,TRUE)==FALSE){
printf("Error sending the packets!\n");
return -1;
}
cpu_time = (clock() - cpu_time)/CLK_TCK;
printf ("\n\nElapsed time: %5.3f\n", cpu_time);
printf ("\nTotal packets generated = %d", npacks);
printf ("\nTotal bytes generated = %d", (Snaplen+24)*npacks);
printf ("\nTotal bits generated = %d", (Snaplen+24)*npacks*8);
printf ("\nAverage packets per second = %d", (int)((double)npacks/cpu_time));
printf ("\nAverage bytes per second = %d", (int)((double)((Snaplen+24)*npacks)/cpu_time));
printf ("\nAverage bits per second = %d", (int)((double)((Snaplen+24)*npacks*8)/cpu_time));
printf ("\n");
PacketFreePacket(lpPacket);
// close the adapter and exit
PacketCloseAdapter(lpAdapter);
return (0);
}

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{1E3BED58-2F2C-463A-B9FD-9A55235C6840}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>Packet.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>Packet.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>Packet.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>Packet.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>Packet.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>Packet.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>Packet.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>Packet.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="TestPacketSend.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,2 @@
These files use the packet.dll API instead of wpcap.dll.
The use of packet.dll API is strongly discouraged.

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{42E5F1D6-6E83-4C13-83CC-C6CD83478C58}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="udpdump.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,256 @@
/*
* Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
* Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino, CACE Technologies
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <pcap.h>
#include <Winsock2.h>
#include <tchar.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
/* 4 bytes IP address */
typedef struct ip_address{
u_char byte1;
u_char byte2;
u_char byte3;
u_char byte4;
}ip_address;
/* IPv4 header */
typedef struct ip_header{
u_char ver_ihl; // Version (4 bits) + Internet header length (4 bits)
u_char tos; // Type of service
u_short tlen; // Total length
u_short identification; // Identification
u_short flags_fo; // Flags (3 bits) + Fragment offset (13 bits)
u_char ttl; // Time to live
u_char proto; // Protocol
u_short crc; // Header checksum
ip_address saddr; // Source address
ip_address daddr; // Destination address
u_int op_pad; // Option + Padding
}ip_header;
/* UDP header*/
typedef struct udp_header{
u_short sport; // Source port
u_short dport; // Destination port
u_short len; // Datagram length
u_short crc; // Checksum
}udp_header;
/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
u_int netmask;
char packet_filter[] = "ip and udp";
struct bpf_program fcode;
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
/* Retrieve the device list */
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; 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 Npcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf_s("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the adapter */
if ( (adhandle= pcap_open(d->name, // name of the device
65536, // portion of the packet to capture.
// 65536 grants that the whole packet will be captured on all the MACs.
PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
1000, // read timeout
NULL, // remote authentication
errbuf // error buffer
) ) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->name);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Check the link layer. We support only Ethernet for simplicity. */
if(pcap_datalink(adhandle) != DLT_EN10MB)
{
fprintf(stderr,"\nThis program works only on Ethernet networks.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
if(d->addresses != NULL)
/* Retrieve the mask of the first address of the interface */
netmask=((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
else
/* If the interface is without addresses we suppose to be in a C class network */
netmask=0xffffff;
//compile the filter
if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0 )
{
fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
//set the filter
if (pcap_setfilter(adhandle, &fcode)<0)
{
fprintf(stderr,"\nError setting the filter.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
printf("\nlistening on %s...\n", d->description);
/* At this point, we don't need any more the device list. Free it */
pcap_freealldevs(alldevs);
/* start the capture */
pcap_loop(adhandle, 0, packet_handler, NULL);
return 0;
}
/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
struct tm ltime;
char timestr[16];
ip_header *ih;
udp_header *uh;
u_int ip_len;
u_short sport,dport;
time_t local_tv_sec;
/*
* Unused variable
*/
(VOID)(param);
/* convert the timestamp to readable format */
local_tv_sec = header->ts.tv_sec;
localtime_s(&ltime, &local_tv_sec);
strftime( timestr, sizeof timestr, "%H:%M:%S", &ltime);
/* print timestamp and length of the packet */
printf("%s.%.6d len:%d ", timestr, header->ts.tv_usec, header->len);
/* retireve the position of the ip header */
ih = (ip_header *) (pkt_data +
14); //length of ethernet header
/* retireve the position of the udp header */
ip_len = (ih->ver_ihl & 0xf) * 4;
uh = (udp_header *) ((u_char*)ih + ip_len);
/* convert from network byte order to host byte order */
sport = ntohs( uh->sport );
dport = ntohs( uh->dport );
/* print ip addresses and udp ports */
printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d\n",
ih->saddr.byte1,
ih->saddr.byte2,
ih->saddr.byte3,
ih->saddr.byte4,
sport,
ih->daddr.byte1,
ih->daddr.byte2,
ih->daddr.byte3,
ih->daddr.byte4,
dport);
}

View File

@ -0,0 +1,492 @@
/*
* Copyright (c) 2005 - 2006
* CACE Technologies, Davis, CA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of CACE Technologies nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/*
* This simple program implements a user-level bridge.
* It opens two adapters specified by the user and starts two threads.
* The first thread receives packets from adapter 1 and sends them down to
* adapter 2. The second thread does the same, but in the opposite
* direction.
*/
#include <signal.h>
#include <pcap.h>
#include <tchar.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
/* Storage data structure used to pass parameters to the threads */
typedef struct _in_out_adapters
{
unsigned int state; /* Some simple state information */
pcap_t *input_adapter;
pcap_t *output_adapter;
}in_out_adapters;
/* Prototypes */
DWORD WINAPI CaptureAndForwardThread(LPVOID lpParameter);
void ctrlc_handler(int sig);
/* This prevents the two threads to mess-up when they do printfs */
CRITICAL_SECTION print_cs;
/* Thread handlers. Global because we wait on the threads from the CTRL+C handler */
HANDLE threads[2];
/* This global variable tells the forwarder threads they must terminate */
volatile int kill_forwaders = 0;
/*******************************************************************/
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum1, inum2;
int i=0;
pcap_t *adhandle1, *adhandle2;
char errbuf[PCAP_ERRBUF_SIZE];
u_int netmask1, netmask2;
char packet_filter[256];
struct bpf_program fcode;
in_out_adapters couple0, couple1;
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
/*
* Retrieve the device list
*/
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; d; d=d->next)
{
printf("%d. ", ++i);
if (d->description)
printf("%s\n", d->description);
else
printf("<unknown adapter>\n");
}
if(i==0)
{
printf("\nNo interfaces found! Make sure Npcap is installed.\n");
return -1;
}
/*
* Get input from the user
*/
/* Get the filter*/
printf("\nSpecify filter (hit return for no filter):");
fgets(packet_filter, sizeof(packet_filter), stdin);
/* Get the first interface number*/
printf("\nEnter the number of the first interface to use (1-%d):",i);
scanf_s("%d", &inum1);
if(inum1 < 1 || inum1 > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Get the second interface number*/
printf("Enter the number of the first interface to use (1-%d):",i);
scanf_s("%d", &inum2);
if(inum2 < 1 || inum2 > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
if(inum1 == inum2 )
{
printf("\nCannot bridge packets on the same interface.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/*
* Open the specified couple of adapters
*/
/* Jump to the first selected adapter */
for(d = alldevs, i = 0; i< inum1 - 1 ;d = d->next, i++);
/*
* Open the first adapter.
* *NOTICE* the flags we are using, they are important for the behavior of the prgram:
* - PCAP_OPENFLAG_PROMISCUOUS: tells the adapter to go in promiscuous mode.
* This means that we are capturing all the traffic, not only the one to or from
* this machine.
* - PCAP_OPENFLAG_NOCAPTURE_LOCAL: prevents the adapter from capturing again the packets
* transmitted by itself. This avoids annoying loops.
* - PCAP_OPENFLAG_MAX_RESPONSIVENESS: configures the adapter to provide minimum latency,
* at the cost of higher CPU usage.
*/
if((adhandle1 = pcap_open(d->name, // name of the device
65536, // portion of the packet to capture.
// 65536 grants that the whole packet will be captured on every link layer.
PCAP_OPENFLAG_PROMISCUOUS | // flags. We specify that we don't want to capture loopback packets, and that the driver should deliver us the packets as fast as possible
PCAP_OPENFLAG_NOCAPTURE_LOCAL |
PCAP_OPENFLAG_MAX_RESPONSIVENESS,
500, // read timeout
NULL, // remote authentication
errbuf // error buffer
)) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->description);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
if(d->addresses != NULL)
{
/* Retrieve the mask of the first address of the interface */
netmask1 = ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
}
else
{
/* If the interface is without addresses we suppose to be in a C class network */
netmask1 = 0xffffff;
}
/* Jump to the second selected adapter */
for(d = alldevs, i = 0; i< inum2 - 1 ;d = d->next, i++);
/* Open the second adapter */
if((adhandle2 = pcap_open(d->name, // name of the device
65536, // portion of the packet to capture.
// 65536 grants that the whole packet will be captured on every link layer.
PCAP_OPENFLAG_PROMISCUOUS | // flags. We specify that we don't want to capture loopback packets, and that the driver should deliver us the packets as fast as possible
PCAP_OPENFLAG_NOCAPTURE_LOCAL |
PCAP_OPENFLAG_MAX_RESPONSIVENESS,
500, // read timeout
NULL, // remote authentication
errbuf // error buffer
)) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->description);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
if(d->addresses != NULL)
{
/* Retrieve the mask of the first address of the interface */
netmask2 = ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
}
else
{
/* If the interface is without addresses we suppose to be in a C class network */
netmask2 = 0xffffff;
}
/*
* Compile and set the filters
*/
/* compile the filter for the first adapter */
if (pcap_compile(adhandle1, &fcode, packet_filter, 1, netmask1) <0 )
{
fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
/* Close the adapters */
pcap_close(adhandle1);
pcap_close(adhandle2);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* set the filter for the first adapter*/
if (pcap_setfilter(adhandle1, &fcode)<0)
{
fprintf(stderr,"\nError setting the filter.\n");
/* Close the adapters */
pcap_close(adhandle1);
pcap_close(adhandle2);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* compile the filter for the second adapter */
if (pcap_compile(adhandle2, &fcode, packet_filter, 1, netmask2) <0 )
{
fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
/* Close the adapters */
pcap_close(adhandle1);
pcap_close(adhandle2);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* set the filter for the second adapter*/
if (pcap_setfilter(adhandle2, &fcode)<0)
{
fprintf(stderr,"\nError setting the filter.\n");
/* Close the adapters */
pcap_close(adhandle1);
pcap_close(adhandle2);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* At this point, we don't need the device list any more. Free it */
pcap_freealldevs(alldevs);
/*
* Start the threads that will forward the packets
*/
/* Initialize the critical section that will be used by the threads for console output */
InitializeCriticalSection(&print_cs);
/* Init input parameters of the threads */
couple0.state = 0;
couple0.input_adapter = adhandle1;
couple0.output_adapter = adhandle2;
couple1.state = 1;
couple1.input_adapter = adhandle2;
couple1.output_adapter = adhandle1;
/* Start first thread */
if((threads[0] = CreateThread(
NULL,
0,
CaptureAndForwardThread,
&couple0,
0,
NULL)) == NULL)
{
fprintf(stderr, "error creating the first forward thread");
/* Close the adapters */
pcap_close(adhandle1);
pcap_close(adhandle2);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Start second thread */
if((threads[1] = CreateThread(
NULL,
0,
CaptureAndForwardThread,
&couple1,
0,
NULL)) == NULL)
{
fprintf(stderr, "error creating the second forward thread");
/* Kill the first thread. Not very gentle at all...*/
TerminateThread(threads[0], 0);
/* Close the adapters */
pcap_close(adhandle1);
pcap_close(adhandle2);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/*
* Install a CTRL+C handler that will do the cleanups on exit
*/
signal(SIGINT, ctrlc_handler);
/*
* Done!
* Wait for the Greek calends...
*/
printf("\nStart bridging the two adapters...\n", d->description);
Sleep(INFINITE);
return 0;
}
/*******************************************************************
* Forwarding thread.
* Gets the packets from the input adapter and sends them to the output one.
*******************************************************************/
DWORD WINAPI CaptureAndForwardThread(LPVOID lpParameter)
{
struct pcap_pkthdr *header;
const u_char *pkt_data;
int res = 0;
in_out_adapters* ad_couple = lpParameter;
unsigned int n_fwd = 0;
/*
* Loop receiving packets from the first input adapter
*/
while((!kill_forwaders) && (res = pcap_next_ex(ad_couple->input_adapter, &header, &pkt_data)) >= 0)
{
if(res != 0) /* Note: res=0 means "read timeout elapsed"*/
{
/*
* Print something, just to show when we have activity.
* BEWARE: acquiring a critical section and printing strings with printf
* is something inefficient that you seriously want to avoid in your packet loop!
* However, since this is a *sample program*, we privilege visual output to efficiency.
*/
EnterCriticalSection(&print_cs);
if(ad_couple->state == 0)
printf(">> Len: %u\n", header->caplen);
else
printf("<< Len: %u\n", header->caplen);
LeaveCriticalSection(&print_cs);
/*
* Send the just received packet to the output adaper
*/
if(pcap_sendpacket(ad_couple->output_adapter, pkt_data, header->caplen) != 0)
{
EnterCriticalSection(&print_cs);
printf("Error sending a %u bytes packets on interface %u: %s\n",
header->caplen,
ad_couple->state,
pcap_geterr(ad_couple->output_adapter));
LeaveCriticalSection(&print_cs);
}
else
{
n_fwd++;
}
}
}
/*
* We're out of the main loop. Check the reason.
*/
if(res < 0)
{
EnterCriticalSection(&print_cs);
printf("Error capturing the packets: %s\n", pcap_geterr(ad_couple->input_adapter));
fflush(stdout);
LeaveCriticalSection(&print_cs);
}
else
{
EnterCriticalSection(&print_cs);
printf("End of bridging on interface %u. Forwarded packets:%u\n",
ad_couple->state,
n_fwd);
fflush(stdout);
LeaveCriticalSection(&print_cs);
}
return 0;
}
/*******************************************************************
* CTRL+C hanlder.
* We order the threads to die and then we patiently wait for their
* suicide.
*******************************************************************/
void ctrlc_handler(int sig)
{
/*
* unused variable
*/
(VOID)(sig);
kill_forwaders = 1;
WaitForMultipleObjects(2,
threads,
TRUE, /* Wait for all the handles */
5000); /* Timeout */
exit(0);
}

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{BB73BFD4-454F-42C8-AFE6-FA890A8BD8FC}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="UserBridge.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,200 @@
/*
* Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
* Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Politecnico di Torino, CACE Technologies
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdio.h>
#include "pcap.h"
#ifndef WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#else
#include <winsock.h>
#include <tchar.h>
BOOL LoadNpcapDlls()
{
TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, TEXT("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}
#endif
// Function prototypes
void ifprint(pcap_if_t *d);
char *iptos(u_long in);
char* ip6tos(struct sockaddr *sockaddr, char *address, int addrlen);
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
char errbuf[PCAP_ERRBUF_SIZE+1];
char source[PCAP_ERRBUF_SIZE+1];
#ifdef WIN32
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
#endif
printf("Enter the device you want to list:\n"
"rpcap:// ==> lists interfaces in the local machine\n"
"rpcap://hostname:port ==> lists interfaces in a remote machine\n"
" (rpcapd daemon must be up and running\n"
" and it must accept 'null' authentication)\n"
"file://foldername ==> lists all pcap files in the give folder\n\n"
"Enter your choice: ");
fgets(source, PCAP_ERRBUF_SIZE, stdin);
source[PCAP_ERRBUF_SIZE] = '\0';
/* Retrieve the interfaces list */
if (pcap_findalldevs_ex(source, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n",errbuf);
exit(1);
}
/* Scan the list printing every entry */
for(d=alldevs;d;d=d->next)
{
ifprint(d);
}
pcap_freealldevs(alldevs);
return 1;
}
/* Print all the available information on the given interface */
void ifprint(pcap_if_t *d)
{
pcap_addr_t *a;
char ip6str[128];
/* Name */
printf("%s\n",d->name);
/* Description */
if (d->description)
printf("\tDescription: %s\n",d->description);
/* Loopback Address*/
printf("\tLoopback: %s\n",(d->flags & PCAP_IF_LOOPBACK)?"yes":"no");
/* IP addresses */
for(a=d->addresses;a;a=a->next) {
printf("\tAddress Family: #%d\n",a->addr->sa_family);
switch(a->addr->sa_family)
{
case AF_INET:
printf("\tAddress Family Name: AF_INET\n");
if (a->addr)
printf("\tAddress: %s\n",iptos(((struct sockaddr_in *)a->addr)->sin_addr.s_addr));
if (a->netmask)
printf("\tNetmask: %s\n",iptos(((struct sockaddr_in *)a->netmask)->sin_addr.s_addr));
if (a->broadaddr)
printf("\tBroadcast Address: %s\n",iptos(((struct sockaddr_in *)a->broadaddr)->sin_addr.s_addr));
if (a->dstaddr)
printf("\tDestination Address: %s\n",iptos(((struct sockaddr_in *)a->dstaddr)->sin_addr.s_addr));
break;
case AF_INET6:
printf("\tAddress Family Name: AF_INET6\n");
if (a->addr)
printf("\tAddress: %s\n", ip6tos(a->addr, ip6str, sizeof(ip6str)));
break;
default:
printf("\tAddress Family Name: Unknown\n");
break;
}
}
printf("\n");
}
/* From tcptraceroute, convert a numeric IP address to a string */
#define IPTOSBUFFERS 12
char *iptos(u_long in)
{
static char output[IPTOSBUFFERS][3*4+3+1];
static short which;
u_char *p;
p = (u_char *)&in;
which = (which + 1 == IPTOSBUFFERS ? 0 : which + 1);
_snprintf_s(output[which], sizeof(output[which]), sizeof(output[which]),"%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
return output[which];
}
char* ip6tos(struct sockaddr *sockaddr, char *address, int addrlen)
{
socklen_t sockaddrlen;
#ifdef WIN32
sockaddrlen = sizeof(struct sockaddr_in6);
#else
sockaddrlen = sizeof(struct sockaddr_storage);
#endif
if(getnameinfo(sockaddr,
sockaddrlen,
address,
addrlen,
NULL,
0,
NI_NUMERICHOST) != 0) address = NULL;
return address;
}

View File

@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{0B27B213-4BF3-4611-B412-A2D09CDE8632}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="iflist.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="iflist.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,108 @@
#include <pcap.h>
#include "misc.h"
/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
/* Retrieve the device list on the local machine */
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; 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 Npcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf_s("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the device */
if ( (adhandle= pcap_open(d->name, // name of the device
65536, // portion of the packet to capture
// 65536 guarantees that the whole packet will be captured on all the link layers
PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
1000, // read timeout
NULL, // authentication on the remote machine
errbuf // error buffer
) ) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->name);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
printf("\nlistening on %s...\n", d->description);
/* At this point, we don't need any more the device list. Free it */
pcap_freealldevs(alldevs);
/* start the capture */
pcap_loop(adhandle, 0, packet_handler, NULL);
return 0;
}
/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
struct tm ltime;
char timestr[16];
time_t local_tv_sec;
/*
* unused variables
*/
(VOID)(param);
(VOID)(pkt_data);
/* convert the timestamp to readable format */
local_tv_sec = header->ts.tv_sec;
localtime_s(&ltime, &local_tv_sec);
strftime( timestr, sizeof timestr, "%H:%M:%S", &ltime);
printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
}

View File

@ -0,0 +1,147 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{66297062-96A0-4F0E-B147-3C8384031232}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="basic_dump.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,99 @@
#include "pcap.h"
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
int res;
char errbuf[PCAP_ERRBUF_SIZE];
struct tm ltime;
char timestr[16];
struct pcap_pkthdr *header;
const u_char *pkt_data;
time_t local_tv_sec;
/* Retrieve the device list on the local machine */
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; 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 Npcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf_s("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the device */
if ( (adhandle= pcap_open(d->name, // name of the device
65536, // portion of the packet to capture.
// 65536 guarantees that the whole packet will be captured on all the link layers
PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
1000, // read timeout
NULL, // authentication on the remote machine
errbuf // error buffer
) ) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->name);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
printf("\nlistening on %s...\n", d->description);
/* At this point, we don't need any more the device list. Free it */
pcap_freealldevs(alldevs);
/* Retrieve the packets */
while((res = pcap_next_ex( adhandle, &header, &pkt_data)) >= 0){
if(res == 0)
/* Timeout elapsed */
continue;
/* convert the timestamp to readable format */
local_tv_sec = header->ts.tv_sec;
localtime_s(&ltime, &local_tv_sec);
strftime( timestr, sizeof timestr, "%H:%M:%S", &ltime);
printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
}
if(res == -1){
printf("Error reading the packets: %s\n", pcap_geterr(adhandle));
return -1;
}
return 0;
}

View File

@ -0,0 +1,147 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{92849630-6B09-409C-A7AD-E91E682558B1}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="basic_dump_ex.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,19 @@
#include <tchar.h>
#include <stdio.h>
BOOL LoadNpcapDlls()
{
_TCHAR npcap_dir[512];
UINT len;
len = GetSystemDirectory(npcap_dir, 480);
if (!len) {
fprintf(stderr, "Error in GetSystemDirectory: %x", GetLastError());
return FALSE;
}
_tcscat_s(npcap_dir, 512, _T("\\Npcap"));
if (SetDllDirectory(npcap_dir) == 0) {
fprintf(stderr, "Error in SetDllDirectory: %x", GetLastError());
return FALSE;
}
return TRUE;
}

View File

@ -0,0 +1,86 @@
#include <stdio.h>
#include <pcap.h>
#include "misc.h"
#define LINE_LEN 16
void dispatcher_handler(u_char *, const struct pcap_pkthdr *, const u_char *);
int main(int argc, char **argv)
{
pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
char source[PCAP_BUF_SIZE];
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
if(argc != 2){
printf("usage: %s filename", argv[0]);
return -1;
}
/* Create the source string according to the new WinPcap syntax */
if ( pcap_createsrcstr( source, // variable that will keep the source string
PCAP_SRC_FILE, // we want to open a file
NULL, // remote host
NULL, // port on the remote host
argv[1], // name of the file we want to open
errbuf // error buffer
) != 0)
{
fprintf(stderr,"\nError creating a source string\n");
return -1;
}
/* Open the capture file */
if ( (fp= pcap_open(source, // name of the device
65536, // portion of the packet to capture
// 65536 guarantees that the whole packet will be captured on all the link layers
PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
1000, // read timeout
NULL, // authentication on the remote machine
errbuf // error buffer
) ) == NULL)
{
fprintf(stderr,"\nUnable to open the file %s.\n", source);
return -1;
}
// read and dispatch packets until EOF is reached
pcap_loop(fp, 0, dispatcher_handler, NULL);
return 0;
}
void dispatcher_handler(u_char *temp1,
const struct pcap_pkthdr *header, const u_char *pkt_data)
{
u_int i=0;
/*
* Unused variable
*/
(VOID)temp1;
/* print pkt timestamp and pkt len */
printf("%ld:%ld (%ld)\n", header->ts.tv_sec, header->ts.tv_usec, header->len);
/* Print the packet */
for (i=1; (i < header->caplen + 1 ) ; i++)
{
printf("%.2x ", pkt_data[i-1]);
if ( (i % LINE_LEN) == 0) printf("\n");
}
printf("\n\n");
}

View File

@ -0,0 +1,147 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{161E7606-F4CD-4A04-AB6B-5837F7818EE1}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="readfile.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,81 @@
#include <stdio.h>
#include <pcap.h>
#include "misc.h"
#define LINE_LEN 16
int main(int argc, char **argv)
{
pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
char source[PCAP_BUF_SIZE];
struct pcap_pkthdr *header;
const u_char *pkt_data;
u_int i=0;
int res;
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
if(argc != 2)
{
printf("usage: %s filename", argv[0]);
return -1;
}
/* Create the source string according to the new WinPcap syntax */
if ( pcap_createsrcstr( source, // variable that will keep the source string
PCAP_SRC_FILE, // we want to open a file
NULL, // remote host
NULL, // port on the remote host
argv[1], // name of the file we want to open
errbuf // error buffer
) != 0)
{
fprintf(stderr,"\nError creating a source string\n");
return -1;
}
/* Open the capture file */
if ( (fp= pcap_open(source, // name of the device
65536, // portion of the packet to capture
// 65536 guarantees that the whole packet will be captured on all the link layers
PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
1000, // read timeout
NULL, // authentication on the remote machine
errbuf // error buffer
) ) == NULL)
{
fprintf(stderr,"\nUnable to open the file %s.\n", source);
return -1;
}
/* Retrieve the packets from the file */
while((res = pcap_next_ex( fp, &header, &pkt_data)) >= 0)
{
/* print pkt timestamp and pkt len */
printf("%ld:%ld (%ld)\n", header->ts.tv_sec, header->ts.tv_usec, header->len);
/* Print the packet */
for (i=1; (i < header->caplen + 1 ) ; i++)
{
printf("%.2x ", pkt_data[i-1]);
if ( (i % LINE_LEN) == 0) printf("\n");
}
printf("\n\n");
}
if (res == -1)
{
printf("Error reading the packets: %s\n", pcap_geterr(fp));
}
return 0;
}

View File

@ -0,0 +1,147 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{3071DFB6-68F8-41EF-A56C-0C7A71B6967C}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<AdditionalDependencies>wpcap.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Link>
<DelayLoadDLLs>wpcap.dll</DelayLoadDLLs>
<AdditionalLibraryDirectories>C:\npcap-sdk-0.1\Lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
<ClCompile>
<AdditionalIncludeDirectories>C:\npcap-sdk-0.1\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;HAVE_REMOTE;WPCAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalOptions>/FS %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="readfile_ex.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,110 @@
#include <pcap.h>
#include "misc.h"
/* prototype of the packet handler */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
int main(int argc, char **argv)
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
pcap_dumper_t *dumpfile;
/* Load Npcap and its functions. */
if (!LoadNpcapDlls())
{
fprintf(stderr, "Couldn't load Npcap\n");
exit(1);
}
/* Check command line */
if(argc != 2)
{
printf("usage: %s filename", argv[0]);
return -1;
}
/* Retrieve the device list on the local machine */
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; 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 Npcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf_s("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the device */
if ( (adhandle= pcap_open(d->name, // name of the device
65536, // portion of the packet to capture
// 65536 guarantees that the whole packet will be captured on all the link layers
PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
1000, // read timeout
NULL, // authentication on the remote machine
errbuf // error buffer
) ) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by Npcap\n", d->name);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Open the dump file */
dumpfile = pcap_dump_open(adhandle, argv[1]);
if(dumpfile==NULL)
{
fprintf(stderr,"\nError opening output file\n");
return -1;
}
printf("\nlistening on %s... Press Ctrl+C to stop...\n", d->description);
/* At this point, we no longer need the device list. Free it */
pcap_freealldevs(alldevs);
/* start the capture */
pcap_loop(adhandle, 0, packet_handler, (unsigned char *)dumpfile);
return 0;
}
/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(u_char *dumpfile, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
/* save the packet on the dump file */
pcap_dump(dumpfile, header, pkt_data);
}

Some files were not shown because too many files have changed in this diff Show More