如何在 Rust 中设置套接字选项 SO_REUSEPORT? [英] How to set the socket option SO_REUSEPORT in Rust?

查看:22
本文介绍了如何在 Rust 中设置套接字选项 SO_REUSEPORT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了 std::net 和 mio 的文档,发现了一些方法,例如 set_nodelayset_keepalive,但我还没有找到在给定套接字上设置其他套接字选项的方法,例如 SO_REUSEPORTSO_REUSEADDR .我该怎么做?

I've read the documentation for std::net and mio, and I've found some methods like set_nodelay and set_keepalive, but I haven't found a way to set other socket options like SO_REUSEPORT and SO_REUSEADDR on a given socket. How can I do this?

推荐答案

因为 SO_REUSEPORT 没有交叉-platform,您将需要深入了解特定于平台的代码.在这种情况下,您可以从套接字获取原始文件描述符,然后使用 libc crate 中的函数、类型和值来设置您想要的选项:

Because SO_REUSEPORT isn't cross-platform, you will need to dip into platform-specific code. In this case, you can get the raw file descriptor from the socket and then use functions, types, and values from the libc crate to set the options you want:

extern crate libc; // 0.2.43

use std::{io, mem, net::TcpListener, os::unix::io::AsRawFd};

fn main() -> Result<(), io::Error> {
    let listener = TcpListener::bind("0.0.0.0:8888")?;

    unsafe {
        let optval: libc::c_int = 1;
        let ret = libc::setsockopt(
            listener.as_raw_fd(),
            libc::SOL_SOCKET,
            libc::SO_REUSEPORT,
            &optval as *const _ as *const libc::c_void,
            mem::size_of_val(&optval) as libc::socklen_t,
        );
        if ret != 0 {
            return Err(io::Error::last_os_error());
        }
    }

    Ok(())
}

我不保证这是设置此选项的正确位置,或者我没有搞砸 unsafe 块中的某些内容,但它确实可以在 macOS 10.12 上编译和运行.

I make no guarantee that this is the right place to set this option, or that I haven't screwed up something in the unsafe block, but it does compile and run on macOS 10.12.

更好的解决方案可能是查看 nix crate,它为大多数 *nix 提供了更好的包装器- 具体代码:

A better solution may be to check out the nix crate, which provides nicer wrappers for most *nix-specific code:

extern crate nix; // 0.11.0

use nix::sys::socket::{self, sockopt::ReusePort};
use std::{error::Error, net::TcpListener, os::unix::io::AsRawFd};

fn main() -> Result<(), Box<Error>> {
    let listener = TcpListener::bind("0.0.0.0:8888")?;
    socket::setsockopt(listener.as_raw_fd(), ReusePort, &true)?;

    Ok(())
}

更好的解决方案可能是查看 net2 crate,它提供了更高级别的方法特别是与网络相关的代码:

An even better solution may be to check out the net2 crate, which provides higher-level methods aimed specifically at networking-related code:

extern crate net2; // 0.2.33

use net2::{unix::UnixTcpBuilderExt, TcpBuilder};

fn main() -> Result<(), std::io::Error> {
    let listener = TcpBuilder::new_v4()?
        .reuse_address(true)?
        .reuse_port(true)?
        .bind("0.0.0.0:8888")?
        .listen(42)?;

    Ok(())
}

这篇关于如何在 Rust 中设置套接字选项 SO_REUSEPORT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆