基于交换机转发实验

实验内容

1、实现对数据结构 mac_port_map 的所有操作,以及数据包的转发和广播操作

- iface_info_t *lookup_port(u8 mac[ETH_ALEN]);

- void insert_mac_port(u8 mac[ETH_ALEN], iface_info_t *iface);

- int sweep_aged_mac_port_entry();

- void broadcast_packet(iface_info_t *iface, const char *packet, int len);

- void handle_packet(iface_info_t *iface, char *packet, int len);

2、使用 iperf 和给定的拓扑进行实验,对比交换机转发与集线器广播的性能

设计思路

iface_info_t *lookup_port(u8 mac[ETH_ALEN]);

该函数的作用是:在转发表中查找对应 mac 地址和 iface 映射的表项。若找到对应的表项,则返回查询 mac 地址对应的 iface

由于交换机转发过程中,会存在另一个线程进行超时表项的清理工作,因此查找操作需要加上锁来确保原子性。

该函数具体实现代码如下:

iface_info_t *lookup_port(u8 mac[ETH_ALEN])
{
    pthread_mutex_lock(&mac_port_map.lock);
    u8 hash_value = hash8((char *)mac, ETH_ALEN);
    mac_port_entry_t * mac_port_entry_pos = NULL;
    list_for_each_entry(mac_port_entry_pos, &mac_port_map.hash_table[hash_value], list) {
        if (mac_cmp(mac_port_entry_pos->mac, mac, ETH_ALEN) == 0) {
            mac_port_entry_pos->visited = time(NULL);
            pthread_mutex_unlock(&mac_port_map.lock);
            return mac_port_entry_pos->iface;
        }
    }
    pthread_mutex_unlock(&mac_port_map.lock);
    return NULL;
}

注:其中mac_cmp为自编函数,作用是比较两个mac地址是否相同。

void insert_mac_port(u8 mac[ETH_ALEN], iface_info_t *iface);

该函数的作用是:当转发表中没有 源mac 地址和对应 iface 的映射表项时,将 源mac 地址与该 iface 插入到转发表当中。

同样的,由于交换机转发过程中,会存在另一个线程进行超时表项的清理工作,因此插入操作同样需要加上锁来确保原子性。

结果验证

利用网络拓扑进行 iperf 测试,本设计的测试结果如下:

Python远程连接交换机 python 交换机_代码

上图中 h1 节点同时接收 h2 节点和 h3 节点,可以看出 h2 节点和 h3 节点的发送带宽分别为 9.56Mbps9.56Mbps,利用率为 95.6%

switch-reference 的结果如下:

Python远程连接交换机 python 交换机_Python_02

上图中 h1 节点同时接收 h2 节点和 h3 节点,可以看出 h2 节点和 h3 节点的发送带宽分别为 9.57Mbps9.57Mbps,利用率为 95.7%。可以看出本设计的结果与标准结果基本相同。

hub-reference 的结果如下:

Python远程连接交换机 python 交换机_Python_03

上图中 h1 节点同时接收 h2 节点和 h3 节点,可以看出 h2 节点和 h3 节点的发送带宽分别为 4.07Mbps4.36Mbps,平均利用率为 42.15%

在本实验中,switch 的带宽利用率比 hub 高出 127%。因此 switch 利用转发表的方式明显比 hub 的直接广播模式效率要高。