linux - 如何通过特定的网络接口(interface)发送?

标签 linux rust gateway

我需要动态地通过不同的网关发送消息。如何做到这一点以及我朝这个方向迈出的第一步必须是什么?

在我的服务器上,我有两个连接:一个是直接连接,另一个是通过 VPN 连接。默认路由是直接连接,但我需要动态更改到 VPN 的连接。

目前我尝试从 libc::bind() 构建套接字,它可以工作,但没有预期的效果。

Changing the outgoing IP不是定义接口(interface)的解决方案。

最佳答案

正如评论中所建议的,我们必须使用 SO_BINDTODEVICE,并且无法逃避 FFI,因为它在内部使用。 这里的工作示例:

extern crate libc;

use libc as c;
use std::ffi::CString;
use std::net::{TcpStream, SocketAddr};
use std::io::{self, Write};
use std::os::unix::io::FromRawFd;
use std::mem;

#[cfg(any(target_os = "linux"))]
fn connect_dev(addr: SocketAddr, link: &str) -> io::Result<TcpStream> {
    let (addr_raw, addr_len) = match addr {
        SocketAddr::V4(ref a) =>
            (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t),
        SocketAddr::V6(ref a) =>
            (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t),
    };

    unsafe {
        let fd = check_os_error(c::socket(c::AF_INET, c::SOCK_STREAM, 0))?;
        check_os_error(c::setsockopt(
            fd,
            c::SOL_SOCKET,
            c::SO_BINDTODEVICE,
            CString::new(link).expect("device name").as_ptr() as *const c::c_void,
            mem::size_of::<CString>() as c::socklen_t,
        ))?;
        check_os_error(c::connect(fd, addr_raw, addr_len))?;

        Ok(TcpStream::from_raw_fd(fd))
    }
}

#[cfg(any(target_os = "linux"))]
pub fn check_os_error(res: c::c_int) -> io::Result<c::c_int> {
    if res == -1 {
        Err(io::Error::from_raw_os_error(unsafe { *c::__errno_location()  as i32 }))
    } else {
        Ok(res)
    }
}

关于linux - 如何通过特定的网络接口(interface)发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52257027/

相关文章:

Linux:停止 tar 命令?

rust - 在 and_then 的类型定义中, T 从哪里来?

types - 有没有办法在 Rust 中接受多种回调?

rust - 为什么使用 rustc 命令构建看不到 crate?

google-cloud-platform - GCP API 网关创建失败并出现内部服务器错误

linux - 如何编写 awk 脚本来列出当前使用系统的用户以及他们登录的次数?

linux - 堆的边界是什么?

Spring Cloud 网关 : How to pass params to custom filter

c - Travis CI 使用非 perl 语言安装 perl 模块

java - <int :gateway xml tag in java DSL in spring - integration? 的模拟是什么