简体   繁体   English

如何确定Linux套接字在C ++中绑定的接口

[英]How to determine which interfaces a Linux socket is bound to in C++

I have been trying to figure this out for a while now. 我一直试图解决这个问题。 Given a Linux socket, how can I 鉴于Linux套接字,我该怎么做

  1. Determine if it is bound? 确定它是否受约束?
  2. If it is bound, determine which subset of network interfaces it bound to on a multihomed system? 如果绑定,请确定它在多宿主系统上绑定到哪个网络接口子集?

In short I have a machine with multiple network cards and a socket that is only bound to a subset of these cards. 简而言之,我有一台带有多个网卡的机器和一个仅与这些卡的子集绑定的套接字。 I want to programmatically detect and log these interfaces after they have been bound else where in our libraries meaning I don't have access to this infnormation at the time of binding. 我想以编程方式检测并记录这些接口,因为它们已被绑定在我们库中的其他位置,这意味着我在绑定时无法访问此信息。

I should also point out that I need an IPV4/6 compatible solution preferably for that works with SCTP sockets (though I'm fine with UDP or TCP solutions for now) 我还应该指出,我需要一个兼容IPV4 / 6的解决方案,因为它适用于SCTP套接字(尽管我现在对UDP或TCP解决方案很好)

The getsockname function returns socket name ie the local socket address. getsockname函数返回套接字名称,即本地套接字地址。 Just call this function for a unbound and a bound socket to determine your socket implementations behavior. 只需为未绑定和绑定的套接字调用此函数,以确定您的套接字实现行为。

EDIT : When you have an AF_INET (ie IPv4) socket, the member sin_addr.S_un.S_addr is identical to the appropriate member in the SOCKADDR_IN struct that you have passed to the bind function. 编辑 :当您有一个AF_INET(即IPv4)套接字时,成员sin_addr.S_un.S_addr与您传递给bind函数的SOCKADDR_IN结构中的相应成员相同。 So if you have bound to INADDR_ANY you get INADDR_ANY when the socket isn't bound to a specific network adapter. 因此,如果您已绑定到INADDR_ANY ,则当套接字未绑定到特定网络适配器时,您将获得INADDR_ANY

I checked this with the socket implementation of my OS (Windows 7). 我用我的操作系统的socket实现(Windows 7)检查了这一点。 If your implementation returns something else, you might experience an undefined behavior caused by a bug somewhere else. 如果您的实现返回其他内容,您可能会遇到由其他地方的错误导致的未定义行为。 Of course you can verify the implementation of the network stack if you have the source code available. 当然,如果您有可用的源代码,您可以验证网络堆栈的实现。

There is no support for binding to a subset of network adapters. 不支持绑定到网络适配器的子集。 You can only bind to one or all. 您只能绑定到一个或所有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM