linux - 是否有原始套接字的安全接口(interface)?

标签 linux sockets network-programming rust

Here据说唯一的办法就是使用libc:

extern crate libc;
extern crate native;
use libc::{c_int, c_void, socket, AF_INET, sockaddr_storage};
use native::io::net::sockaddr_to_addr;
use std::io::net::ip::SocketAddr;
static SOCK_RAW: c_int = 3;
static IPPROTO_ICMP: c_int = 1;

fn recvfrom<'buf>(sock: c_int, buf: &'buf mut [u8]) -> (&'buf mut [u8], SocketAddr) {
  let mut storage: sockaddr_storage = unsafe { std::mem::init() };
  let storagep = &mut storage as *mut _ as *mut libc::sockaddr;
  let mut addrlen = std::mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t;

  let bytes = unsafe { libc::recvfrom(sock,
                 buf.as_mut_ptr() as *mut c_void,
                 buf.len() as u64, 
                 0, storagep, &mut addrlen) };

  (buf.mut_slice_to(bytes as uint),
   sockaddr_to_addr(&storage, addrlen as uint).unwrap())
}

fn main() {
  let handle = unsafe { socket(AF_INET, SOCK_RAW, IPPROTO_ICMP) };
  println!("{}", handle);
  let mut bufferator = [0, ..2048];
  loop {
    let (buf, from) = recvfrom(handle, bufferator.as_mut_slice());
    println!("from {}, data:\n{}", from, buf);
  }
}

但是这是一年前写的,所以事情可能已经改变了?

最佳答案

一般来说,对于任意 C 代码不存在安全接口(interface),因为 C 代码不能保证不做安全 Rust 不允许的事情。尽管只是约定俗成,但 Rust 领域中许多在名称中说“原始”的东西都具有不安全的语义。

您可以做的是用 Rust 代码包装原始 C 代码,以确保 C 代码永远不会进入违反程序安全的状态。这就是 TcpStream 这样的项目或 UdpSocket被 build 。据我所知,没有用于 ICMP 套接字的包装器。

关于linux - 是否有原始套接字的安全接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33714116/

相关文章:

sockets - 301 与 socket.http 永久移动

linux - linux系统如何删除时间晚于系统时间的文件

java - 在不打开 IO 流的情况下识别丢失的 Socket 连接

linux - 如何在自己的进程组中启动一个进程?

sockets - 套接字编程初学者

python - 在网络上的另一台计算机上启动进程

c# - 忽略 TcpClient/NetworkStream 中的传入数据

java - 尝试连接到 Symantec NetBackup 时 JSch 中出现 "Algorithm negotiation fail"错误 - 远程抓取报告

c++ - "tailing"C/C++ (Linux) 中使用 inotify 的多个文件(竞争条件?)

javascript - 找不到 PhantomJS 的故障转储