加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

c – 如何使用具有Boost Asio套接字的特定网络接口/ Ip?

发布时间:2020-05-23 12:28:04 所属栏目:Linux 来源:互联网
导读:我有一个Debian / linux服务器,它有几个IP地址,都分配给同一个物理网卡. / etc / network / interfaces配置文件如下所示(xx代表数字)auto lo iface lo inet loopback auto eth0 iface eth0 inet static address 176.xx.xx.144

我有一个Debian / linux服务器,它有几个IP地址,都分配给同一个物理网卡. / etc / network / interfaces配置文件如下所示(xx代表数字)

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
    address 176.xx.xx.144
    netmask 255.255.255.0
    network 176.xx.xx.0
    broadcast 176.xx.xx.255
    gateway 176.xx.xx.254

auto eth0:0
allow-hotplug eth0:0
iface eth0:0 inet static
    address 46.xx.xx.57
    netmask 255.255.255.255
    broadcast 46.xx.xx.57

auto eth0:1
allow-hotplug eth0:1
iface eth0:1 inet static
    address 94.xx.xx.166
    netmask 255.255.255.255
    broadcast 94.xx.xx.166

//IPv6 Stuff...

我正在使用Boost Asio处理所有网络连接的客户端应用程序.在此应用程序中,我希望能够使用特定的网络接口/ IP地址连接到外部服务器.我发现this类似的问题,但只是将boost :: asio :: ip :: tcp :: socket绑定到一个specfic端点,然后连接到外部服务器不起作用.这是我尝试过的最小工作示例:

#include 

当我在我的服务器上运行时,我得到:

Before binding socket has local endpoint: 0.0.0.0:0
Before connecting socket has local endpoint: 94.xx.xx.166:38399
After connecting socket has local endpoint: 176.xx.xx.144:45959
External server says we are using IP: 176.xx.xx.144

现在我有点迷茫,因为我不知道还有什么可以尝试.我不一定需要一个可移植的解决方案,任何适用于这个Debian设置的东西都可以.

更新

我将为我的设置提供解决方案.如有必要,我可以更改/ etc / network / interfaces配置文件.但是,为了重用我的代码,任何解决方案都必须使用Boost Asio套接字(至少作为包装器).

最佳答案 要绑定到特定接口,您必须首先打开连接.你做到了 – 到目前为止一切顺利.但之后你调用boost :: asio :: connect(socket,remoteEndpoint);这将关闭你的连接(作为服务,所以说).

Boost告诉你它确实如此 – 但你必须仔细观察.在参数下参考重载版本的连接,你正在使用它会说

Parameters

s

The socket to be connected. If the socket is already open,it will be closed.

或者在boost / asio / impl / connect.hpp中的实现:

// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License,Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

[...]

template 

(注意s.close(ec);)

解决方案

应该很简单.替换boost :: asio :: connect … by

socket.connect(*remoteEndpoint);

(或者在相应的远程端点上循环,如果需要,类似于boost源代码.)

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读