# 实验九

这次实验也比较简单，但是我感觉实验文档还是有些模糊的小地方，以及有个严重的bug,所以我还是再写一点。

{% hint style="danger" %}
最重要：去掉一个注释
{% endhint %}

实验框架里handle\_packet函数里有这样一个log:

```c
log(DEBUG, "the dst mac address is " ETHER_STRING ".\n", ETHER_FMT(eh->ether_dhost));
```

这个log如果你不注释掉，如果你只在一个终端执行测试可能会使你的测试跑的带宽特别慢，并且执行一次iperf后再执行别的就会报错： tcp: no route to host,你的oj的两个测试都过不去。

经助教研究，可能是测试指令中有 &导致了缓冲区的缓存的并发bugs,所以最简单的方法：把这个注释删了。

同时你也最好别添加其他会导致重定向的log。

***

### 关于几个函数个人的思路

~~实验文档里的函数解释有点怪，和代码实际逻辑有点区别（虽然做的事一样）~~

因此我写一下自己的函数思路。

```
// handle_packet - 交换机数据包处理函数
// 参数:
// iface: 数据包的入接口
// packet: 数据包内容
// len: 数据包长度
void handle_packet(iface_info_t *iface, char *packet, int len) {
// 1. 数据包解析
struct ether_header *eh = (struct ether_header *)packet;
// 2. 查找目的MAC对应接口（lookup_port）

// 3. 转发处理
    // 3.1 未找到目的接口,执行广播broadcast_packet
    // 3.2 找到目的接口,单播转发(iface_send_packet)

// 4. MAC地址学习(源mac lookup_port)
    // 源MAC不在表中,添加MAC-接口映射(insert_mac_port)
    

// 5. 释放数据包内存
free(packet);
}
```

广播函数和实验8一样，直接copy就行。

```
// lookup_port - 在MAC地址转发表中查找指定MAC地址的接口
// 使用struct: iface_info_t,mac_port_entry_t
//用memcmp比较
iface_info_t *lookup_port(u8 *mac) {
// 1. 计算MAC地址的哈希值(hash8函数)
// 2. 加锁，在哈希桶的链表中查找MAC地址
// 3. 找到则更新访问时间并返回接口
// 4. 未找到返回NULL
}
```

```
// insert_mac_port - 将MAC地址和接口的对应关系插入转发表
//用memcmp,memcpy,list_add_head,mac_port_entry_t
void insert_mac_port(u8 *mac, iface_info_t *iface) {
    // 1. 计算MAC地址的哈希值
    // 2. 加锁，检查MAC是否已在表中
    // 3. 若存在则更新接口和时间(visited)
    // 4. 若不存在则创建新表项并插入链表头部
}
```

```
// sweep_aged_mac_port_entry - 清理超时的MAC表项 
//善用time(NULL),宏HASH_8BITS,MAC_PORT_TIMEOUT
int sweep_aged_mac_port_entry() {
    // 1. 遍历所有哈希桶(hash8)
    // 2. 检查每个表项的最后访问时间
    // 3. 删除超过30s未访问的表项
    // 4. 返回删除数量
}
```

写完了就结束啦！


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blueroaring-njus-organization.gitbook.io/njucs_25spring_network-exp_additional/shi-yan-jiu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
