如何获取与 TCP 套接字关联的接口名称/索引? [英] How can I get the interface name/index associated with a TCP socket?

查看:21
本文介绍了如何获取与 TCP 套接字关联的接口名称/索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 TCP 服务器,它需要知道每个连接来自哪个接口.我无法使用地址/子网来推断使用了哪个接口,因为可能存在具有相同地址/子网值的接口.它基于 Linux,无需代码可移植.

I'm writing a TCP server that needs to know which interface each connection arrived from. I cannot use the address/subnet to deduce which interface was used, since there might be interfaces with the same address/subnet values. It's Linux based, and there's no need for the code to be portable.

我所能找到的只是获取所有接口的函数,或者通过索引获取单个接口的函数.我找不到任何方法来获取与接受的 TCP 套接字关联的接口.

All I could find were functions to get all interfaces, or a single interface by index. I could not find any way to get the interface associated with an accepted TCP socket.

有什么想法吗?我错过了什么?

Any ideas? Something I've missed?

重申一下,IP 地址在我的情况下不是唯一的.既不是目标地址(服务器本身)也不是源地址(客户端).是的,这是一个非常极端的IP方案.

To reiterate, IP addresses are not unique in my case. Neither the destination addresses (the server itself) nor the source addresses (the clients). Yes, this is a very extreme IP scheme.

推荐答案

使用 getsockname() 获取 TCP 连接本地端的 IP.然后使用getifaddrs()找到对应的接口:

Use getsockname() to get IP of local end of the TCP connection. Then use getifaddrs() to find the corresponding interface:

struct sockaddr_in addr;
struct ifaddrs* ifaddr;
struct ifaddrs* ifa;
socklen_t addr_len;

addr_len = sizeof (addr);
getsockname(sock_fd, (struct sockaddr*)&addr, &addr_len);
getifaddrs(&ifaddr);

// look which interface contains the wanted IP.
// When found, ifa->ifa_name contains the name of the interface (eth0, eth1, ppp0...)
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
{
    if (ifa->ifa_addr)
    {
        if (AF_INET == ifa->ifa_addr->sa_family)
        {
            struct sockaddr_in* inaddr = (struct sockaddr_in*)ifa->ifa_addr;

            if (inaddr->sin_addr.s_addr == addr.sin_addr.s_addr)
            {
                if (ifa->ifa_name)
                {
                    // Found it
                }
            }
        }
    }
}
freeifaddrs(ifaddr);

以上只是一个肮脏的例子,需要一些修改:

Above is just a dirty example, some modifications are needed:

  1. 添加缺失的错误检查
  2. IPv6 支持

这篇关于如何获取与 TCP 套接字关联的接口名称/索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆