-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsend.rs
More file actions
56 lines (47 loc) · 1.69 KB
/
send.rs
File metadata and controls
56 lines (47 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use std::{error, fmt, io};
use crate::syscall;
#[derive(Debug)]
pub enum Error {
Accept(syscall::accept::Error),
Send(io::Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Accept(err) => {
write!(f, "failed to get accepted connection sock fd: {}", err)
}
Error::Send(err) => write!(f, "send err: {}", err),
}
}
}
impl error::Error for Error {}
impl From<syscall::accept::Error> for Error {
fn from(value: syscall::accept::Error) -> Self {
Self::Accept(value)
}
}
// EXAMPLE: Send an arbitrary data "hello world!" to socket created for an accepted connection to localhost, to port 3490.
// MANPAGE:
// man 2 send (Linux)
// man 3 send (POSIX)
pub fn send() -> Result<(), Error> {
// NOTE: Since the example about `send()` is a pseudo-code, it is decided to use `accept()` to set up the process beforehand.
let conn_sock_fd = syscall::accept()?;
let buf = b"hello world!\n";
let len = buf.len();
// SAFETY: For example purposes, the `send()` call is explicitly not checked to see whether all of buf is sent through the sock or not.
// `send()` is just checked to see whether it succeeded or not.
// Since the `conn_sock_fd` contains a initialized socket, and a fixed buf is used, it is safe to use `send()`.
unsafe {
let bytes_sent = libc::send(conn_sock_fd, buf.as_ptr() as *const libc::c_void, len, 0);
match bytes_sent {
-1 => {
let err = io::Error::last_os_error();
Err(Error::Send(err))
}
_ => Ok(()),
}
}?;
Ok(())
}