• lwip多网卡自适应选择


    当系统中有多个网卡时,lwip会选择第一个网卡作为默认网卡,ping、tftp、iperf都会选择第一个网卡来进行,没有办法使用第二个网卡(一些命令可以通过-i选项选择网卡,有些命令则没有提供),此时需要修改lwip中发送数据时网卡选择的逻辑。

    首先找到LWIP_HOOK_IP4_ROUTE_SRC宏,该宏的定义如下:

    1. #ifdef LWIP_HOOK_IP4_ROUTE_SRC
    2. struct netif *lwip_ip4_route_src(const ip4_addr_t *dest, const ip4_addr_t *src)
    3. {
    4. struct netif *netif;
    5. /* iterate through netifs */
    6. for (netif = netif_list; netif != NULL; netif = netif->next)
    7. {
    8. /* is the netif up, does it have a link and a valid address? */
    9. if (netif_is_up(netif) && netif_is_link_up(netif) && !ip4_addr_isany_val(*netif_ip4_addr(netif)))
    10. {
    11. /* gateway matches on a non broadcast interface? (i.e. peer in a point to point interface) */
    12. if (src != NULL)
    13. {
    14. if (ip4_addr_cmp(src, netif_ip4_addr(netif)))
    15. {
    16. return netif;
    17. }
    18. }
    19. }
    20. }
    21. netif = netif_default;
    22. return netif;
    23. }
    24. #endif /* LWIP_HOOK_IP4_ROUTE_SRC */

    可知,当上层有数据要发送时,lwip会查找已注册的网卡中适合的网卡,条件为:网卡已启动、网卡链接成功、已获取到ip,如果指定了源ip则在符合上述条件的网卡中找到和源ip地址一致的网卡,否则使用默认网卡。显然,当系统中有第二个网卡时,最终会找不到第二个网卡,最后仍使用默认网卡,需要修改成如下所示:

    1. #ifdef LWIP_HOOK_IP4_ROUTE_SRC
    2. struct netif *lwip_ip4_route_src(const ip4_addr_t *dest, const ip4_addr_t *src)
    3. {
    4. struct netif *netif = RT_NULL, *netif_alt = RT_NULL;
    5. /* iterate through netifs */
    6. for (netif = netif_list; netif != NULL; netif = netif->next)
    7. {
    8. /* is the netif up, does it have a link and a valid address? */
    9. if (netif_is_up(netif) && netif_is_link_up(netif) && !ip4_addr_isany_val(*netif_ip4_addr(netif)))
    10. {
    11. /* gateway matches on a non broadcast interface? (i.e. peer in a point to point interface) */
    12. if (src != NULL)
    13. {
    14. if (ip4_addr_cmp(src, netif_ip4_addr(netif)))
    15. {
    16. return netif;
    17. }
    18. else if((dest->addr & IN_CLASSA_HOST) == (netif->ip_addr.addr & IN_CLASSA_HOST))
    19. {
    20. netif_alt = netif;
    21. }
    22. }
    23. }
    24. }
    25. if(netif_alt)
    26. netif = netif_alt;
    27. else
    28. netif = netif_default;
    29. return netif;
    30. }
    31. #endif /* LWIP_HOOK_IP4_ROUTE_SRC */

    来张代码对比图,可以清晰的看到修改的部分:

  • 相关阅读:
    Android C++系列:Linux网络(三)协议格式
    2.线性表——数据结构学习
    手把手教你如何Vue项目打包dist文件并Tomcat发布【超级详细】
    十大网站助力人工智能学习之路
    Netty编码和解码
    HttpStatusCodeException.getResponseBodyAsString 乱码
    EPSON机器人与PC上位机软件C#网络TCP通讯
    一起Talk Android吧(第三百四十三回: Android网络编程总结)
    1.4_16 Axure RP 9 for mac 高保真原型图 - 案例15 【动态面板-滚动条5】深色模式 - 按钮效果升级
    数学建模常见四大赛题
  • 原文地址:https://blog.csdn.net/qq_27575841/article/details/134005408