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

查看:311
本文介绍了如何获得与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天全站免登陆