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

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

问题描述

我已经阅读了std::net和mio的文档,并且找到了set_nodelayset_keepalive之类的一些方法,但是我还没有找到设置诸如SO_REUSEPORTSO_REUSEPORT的其他套接字选项的方法.给定套接字上的SO_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并非跨平台,您将需要研究特定于平台的代码.在这种情况下,您可以从套接字获取原始文件描述符,然后使用libc板条箱中的函数,类型和值来设置所需的选项:

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(())
}

我不保证这是设置此选项的正确位置,或者我没有在不安全的代码块中弄乱某些内容,但是它确实可以在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板条箱,它为大多数情况提供了更好的包装器* 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板条箱,它提供了更高级别的方法专门针对与网络相关的代码:

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天全站免登陆