如何通过特定的网络接口发送?

问题描述 投票:0回答:2

我需要动态地通过不同的网关发送消息。这是怎么做的,这是我迈向这个方向的第一步?

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

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

Changing the outgoing IP不是定义界面的解决方案。

linux rust gateway
2个回答
0
投票

您可以使用不同的源IP。我假设您已将系统配置为将不同的源IP路由到不同的网关(如果不是,则是操作员问题,而不是程序员)。您可以在bind函数中为套接字指定不同的源IP。通常你传递'默认'值(0.0.0.0),这意味着'任何操作系统找到合理的',但你可以为你的任务指定确切的源IP。

C bind签名:

int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

addr可能包含特定地址。


0
投票

正如评论中所建议的那样,我们必须使用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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.