#3.2. net::: 네트워크(TCP / UDP / Unix + TLS 1.3)
이 페이지의 내용
std::net 모듈은 저수준 네트워크 기본 요소와 TLS 1.3을 한 묶음으로 정의합니다. HTTP, HTTP/2, HTTP/3 같은 고수준 프로토콜은 일부러 범위 밖에 두고 http 등 별도 패키지에 맡깁니다. Go는 표준 라이브러리가 1.0에서 동결된 뒤 발전이 멈췄습니다. 이 선택은 그 전철을 피하려는 것이기도 합니다.
#3.2.0. 공통 규칙
net은 같은 소켓을 세 층으로 다룹니다.
| 층 | 항목 | 정해 두는 것 |
|---|---|---|
| 저수준 | Socket(3.2.9) | 없음: 도메인, 타입, 프로토콜, 모든 옵션을 호출자가 정하고, 호출 하나가 시스템 호출 하나입니다 |
| 타입별 | TcpStream::connect, TcpListener::bind, UdpSocket::bind / connect / send_to | 소켓 타입. 주소는 ToSocketAddrs(3.2.4)로 받습니다 |
| 편의 | tcp_connect, tcp_listen, udp_bind(3.2.6) | 같은 호출을 자유 함수로 |
- tier 공통 인자 규약이 적용됩니다.
Path매개변수는P: AsPath입니다. 쓰는 데이터(write/write_all/send/send_to/send_with_fd와 그_async판)는AsBytes로str,List<u8>,Slice<u8>를 받습니다. 읽는 버퍼는SliceMut<u8>입니다(2.23.1).read(buf)는buf의 앞n바이트를 채우고n을 돌려줍니다.0은 스트림의 끝입니다. - 소켓 타입은 OS 핸들이고 affine입니다(2.13.4).
let b = s는 소켓을 옮깁니다. fd를 복제하는 것은try_clone뿐입니다. - 소켓(
Socket,TcpStream,TcpListener,UdpSocket, Unix 소켓),tls::Client/tls::Server, 나눈 연결의 반쪽(ReadHalf/WriteHalf, 반쪽으로 나누기)은io::Close를 구현합니다(2.23.3). 닫기는 실패할 수 있으므로 소유자가try s.close()나using(2.13.4)으로 하나하나 닫습니다. 열어 둔 채 스코프를 벗어나면 컴파일 에러입니다.Drop은 에러가 빠져나가는 경로에서만 해제하고, 닫기의 에러는 버립니다. 닫힌 소켓을 쓰면IoError(InvalidInput)입니다. 다른 task가 소켓을 닫으면 그 소켓에서 대기 중인*_async연산은 이 에러로 끝납니다.shutdown(Read | Both)뒤에는 대기 중인 읽기가 0으로 끝납니다. TcpStream,os::unix::net::UnixStream, 나눈 연결의 반쪽(ReadHalf는 읽기 트레잇,WriteHalf는 쓰기 트레잇. 반쪽으로 나누기)은io::Read+io::Write와io::AsyncRead+io::AsyncWrite를 구현합니다(2.23). 읽기와 쓰기는 이 트레잇 메서드이고, 같은 이름의 고유 메서드는 없습니다. 중단된 동안 취소된 읽기나 쓰기는 바이트를 옮기지 않은 상태입니다. 모든 소켓과 TLS 연결은io::AsyncClose를 구현합니다.try await s.close_async()처럼 씁니다.*_async메서드는ref self를 받습니다(0.5.13).
#블로킹과 *_async
메서드는 두 벌입니다.
| 형태 | 기다리는 방식 |
|---|---|
accept, read, write .. | 호출한 OS 스레드를 막습니다 (task 안이면 그 워커도 막음) |
accept_async, read_async .. | task만 중단하고 워커는 다른 task를 실행합니다 |
*_async 메서드는 async fn이고, try await s.read_async(buf)처럼 씁니다. 준비 대기는 I/O 드라이버가 맡습니다. 일반 함수는 스택 없는 코루틴을 중단할 수 없습니다. 그래서 같은 이름의 동기 호출이 task 안에서 저절로 중단되지는 않습니다.
| 블로킹 | async |
|---|---|
TcpListener::accept | TcpListener::accept_async |
TcpStream::connect | TcpStream::connect_async |
Socket::connect / accept | Socket::connect_async / accept_async |
Read::read | AsyncRead::read_async |
Read::read_to_end | AsyncRead::read_to_end_async |
Write::write | AsyncWrite::write_async |
Write::write_all | AsyncWrite::write_all_async |
Write::flush | AsyncWrite::flush_async |
Close::close | AsyncClose::close_async |
TcpStream::shutdown (Socket, UnixStream도) | shutdown_async |
UdpSocket::connect | UdpSocket::connect_async |
UdpSocket::send_to | UdpSocket::send_to_async |
UdpSocket::recv_from | UdpSocket::recv_from_async |
UdpSocket::send | UdpSocket::send_async |
UdpSocket::recv | UdpSocket::recv_async |
Socket::send_to / recv_from | Socket::send_to_async / recv_from_async |
UnixListener::accept | UnixListener::accept_async |
UnixDatagram::connect / send / recv | UnixDatagram::connect_async / send_async / recv_async |
send_with_fd / recv_with_fd (UnixStream, UnixDatagram) | send_with_fd_async / recv_with_fd_async |
tcp_connect | tcp_connect_async |
tls::Client::new / with_config | tls::Client::new_async / with_config_async |
tls::Server::new | tls::Server::new_async |
tls::Client::read ... key_update (Server도) | read_async ... key_update_async |
UnixStream의 읽기와 쓰기는 Read / Write 행입니다. 타입별 전체 목록은 0.5.13에 있습니다.
타임아웃은 블로킹 쪽에만 적용됩니다(set_read_timeout / set_write_timeout, 넘으면 TimedOut). async 쪽은 task::timeout(task를 기다림)이나 task::select(2.18.1)로 감쌉니다. select는 진 쪽을 취소하므로 읽기를 포기할 때 쓰기 좋습니다.
enum Got { Data(usize), Timeout }
let (_, got) = await task::select([
async { Got::Data(try await s.read_async(buf) catch _ { 0 }) },
async { await task::sleep(Duration::secs(5)); Got::Timeout },
]);
set_nonblocking(true)이면 블로킹 메서드는 기다리지 않고 WouldBlock을 던집니다.
wasm32-wasip2에서 std::net(TCP / UDP connect, bind, listen, accept, DNS)은 wasi:sockets로 동작합니다. 호스트가 네트워크 접근을 허락해야 합니다(예: wasmtime -S inherit-network -S allow-ip-name-lookup). wasm32-wasip1-threads에서는 TcpListener::inherited()의 listener만 동작합니다. connect / bind / DNS는 Unsupported를 던집니다.
#3.2.1. TCP
TCP는 TcpListener와 TcpStream 두 타입이 중심입니다. 리스너는 bind와 accept를 맡습니다. 스트림은 읽기·쓰기와 옵션 제어를 맡습니다.
struct TcpListener { /* OS handle */ }
struct TcpStream { /* OS handle */ }
impl TcpListener {
fn bind<A: ToSocketAddrs>(addr: A) throws (IoError) -> TcpListener; // 처음으로 bind 되는 주소;
// SO_REUSEADDR (Windows 제외), backlog 128
fn inherited() -> List<TcpListener>; // host 가 프로세스에 넘긴 listener
fn accept(self) throws (IoError) -> (TcpStream, SocketAddr);
async fn accept_async(ref self) throws (IoError) -> (TcpStream, SocketAddr);
fn local_addr(self) throws (IoError) -> SocketAddr; // port 0 으로 bind 한 뒤 실제 port
fn try_clone(self) throws (IoError) -> TcpListener;
fn set_nonblocking(self, nb: bool);
fn incoming(ref self) -> Incoming; // 뷰; TryIterator<Item = TcpStream, Error = IoError>
fn into_incoming(self) -> io::Owned<Incoming, TcpListener>; // listener 를 소유
fn set_ttl(self, ttl: u32) throws (IoError); // IP_TTL
fn ttl(self) throws (IoError) -> u32;
fn close(self) throws (IoError); // OS 가 알린 에러를 던짐
}
impl TcpStream {
fn connect<A: ToSocketAddrs>(addr: A) throws (IoError) -> TcpStream; // 처음으로 받아 주는 주소
fn connect_timeout(addr: SocketAddr, dur: Duration) throws (IoError) -> TcpStream;
async fn connect_async<A: ToSocketAddrs>(addr: A) throws (IoError) -> TcpStream;
fn peer_addr(self) throws (IoError) -> SocketAddr;
fn local_addr(self) throws (IoError) -> SocketAddr;
fn shutdown(self, how: Shutdown) throws (IoError);
async fn shutdown_async(ref self, how: Shutdown) throws (IoError); // shutdown 은 기다리지 않음
fn try_clone(self) throws (IoError) -> TcpStream;
fn split(self) -> (ReadHalf<TcpStream>, WriteHalf<TcpStream>); // 아래 반쪽으로 나누기
fn close(self) throws (IoError); // OS 가 알린 에러를 던짐
// TCP 옵션
fn set_nodelay(self, nodelay: bool) throws (IoError); // TCP_NODELAY
fn nodelay(self) throws (IoError) -> bool;
fn set_ttl(self, ttl: u32) throws (IoError); // IP_TTL
fn ttl(self) throws (IoError) -> u32;
fn set_keepalive(self, alive: Duration | none) throws (IoError); // SO_KEEPALIVE + idle (초), none = 끔
fn set_read_timeout(self, dur: Duration | none);
fn set_write_timeout(self, dur: Duration | none);
fn read_timeout(self) -> Duration | none;
fn write_timeout(self) -> Duration | none;
fn set_nonblocking(self, nb: bool);
}
impl io::Read for TcpStream { ... } // read, read_to_end, ..
impl io::Write for TcpStream { ... } // write, write_all, flush (no-op)
impl io::AsyncRead for TcpStream { ... }
impl io::AsyncWrite for TcpStream { ... }
impl io::Close for TcpStream { ... }
impl io::Close for TcpListener { ... }
impl io::AsyncClose for TcpStream { ... }
impl io::AsyncClose for TcpListener { ... }
impl Drop for TcpStream { ... } // 에러 경로에서 해제
impl Drop for TcpListener { ... }
impl From<Socket> for TcpStream { ... } // 연결된 stream Socket (3.2.9)
impl From<Socket> for TcpListener { ... } // bind 하고 listen 하는 stream Socket
enum Shutdown { Read, Write, Both }
TcpListener::inherited()는 호스트가 프로세스에 넘긴 listener를 돌려줍니다. WASI에서는 미리 연 소켓이고, Unix에서는 systemd LISTEN_FDS 소켓 활성화입니다. Windows에서는 없습니다.
Incoming은 listener의 범위 한정 뷰이고(2.23.1. listener의 범위 안에 머물며 listener는 여전히 소유자가 닫습니다. 자기 task에서 도는 루프에는 listener를 소유하는 into_incoming()을 씁니다) TryIterator입니다(2.7.13). next마다 accept를 한 번 호출하고, accept가 실패하면 try for 루프가 그 에러로 끝납니다. 스스로 끝나지는 않습니다. 쓰는 도중 상대가 닫아도 SIGPIPE로 프로세스가 끝나지 않습니다. 대신 쓰기가 IoError(BrokenPipe)를 냅니다.
#반쪽으로 나누기
split은 연결을 읽기 반쪽과 쓰기 반쪽으로 나눕니다. 한 task나 스레드가 읽는 동안 다른 쪽이 쓸 수 있습니다. TcpStream, os::unix::net::UnixStream(3.10.4), tls::Client, tls::Server(3.2.5)에 있고, T는 반쪽이 나온 연결의 타입입니다.
struct ReadHalf<T> { .. } // Send, Sync 아님: 소유자 하나
struct WriteHalf<T> { .. } // Send, Sync 아님: 소유자 하나
impl<T> ReadHalf<T> {
fn close(self) throws (IoError); // 두 반쪽이 모두 닫히면 소켓이 닫힘
fn shutdown(self, how: Shutdown) throws (IoError); // 함께 쓰는 소켓 (아래)
async fn shutdown_async(ref self, how: Shutdown) throws (IoError);
}
impl<T> WriteHalf<T> {
fn close(self) throws (IoError); // 상대에게 스트림의 끝을 알림 (아래)
fn shutdown(self, how: Shutdown) throws (IoError);
async fn shutdown_async(ref self, how: Shutdown) throws (IoError);
}
impl ReadHalf<TcpStream> {
fn unsplit(self, w: WriteHalf<TcpStream>) -> TcpStream;
}
// ReadHalf<UnixStream>, ReadHalf<tls::Client>, ReadHalf<tls::Server> 도 같음
impl<T> io::Read for ReadHalf<T> { ... }
impl<T> io::AsyncRead for ReadHalf<T> { ... }
impl<T> io::Write for WriteHalf<T> { ... }
impl<T> io::AsyncWrite for WriteHalf<T> { ... }
impl<T> io::Close for ReadHalf<T> { ... } // WriteHalf<T> 도; 둘 다 io::AsyncClose
impl<T> Drop for ReadHalf<T> { ... } // WriteHalf<T> 도: 에러 경로에서 해제
split은 연결을 반쪽들로 옮깁니다. let b = s처럼 원래 바인딩은 옮겨진 상태가 됩니다(2.13.4). 각 반쪽은 자기 방향의 affine 소유자이고, 다른 소켓처럼 소유자가 닫습니다(3.2.0). 어느 쪽도 연결의 두 번째 핸들이 아닙니다. 읽기 반쪽이 읽은 것을 쓰기 반쪽은 보지 못하고, 두 반쪽은 두 스레드나 task에서 동시에 쓸 수 있습니다.
읽기 반쪽이 열려 있을 때 쓰기 반쪽을 닫으면 상대에게 스트림이 끝납니다. shutdown(Write)를 하고(TLS 쓰기 반쪽은 먼저 close_notify를 보냄), 상대의 읽기는 그 뒤 0을 돌려줍니다. 읽기 반쪽은 응답을 계속 읽습니다. 읽기 반쪽만 닫으면 아무것도 보내지 않습니다. 상대가 보내는 데이터를 더 읽지 않을 뿐이고, 소켓은 쓰기 반쪽을 위해 열려 있습니다. 두 번째 반쪽을 닫을 때 소켓이 닫히고(TLS 연결은 이때 키를 지움), 그 닫기는 OS가 알린 에러를 던집니다. 반쪽의 close_async는 close와 같고, 블로킹하는 대신 task를 중단합니다.
shutdown은 소켓에 대한 연산이므로 두 반쪽 모두 shutdown(how)이 있고, 두 반쪽이 함께 쓰는 소켓에 작용합니다. Read, Write, Both는 TcpStream::shutdown과 같습니다. 어느 반쪽에서든 Both를 하면 POSIX shutdown(SHUT_RDWR)처럼(Windows에서는 SD_BOTH) 다른 반쪽에서 막혀 있는 읽기나 쓰기가 깨어납니다. 대기 중인 읽기는 0을 돌려주고, 대기 중인 쓰기는 실패합니다. TLS 연결에서 Write와 Both는 먼저 close_notify를 보냅니다. 쓰기를 이미 shutdown한 쓰기 반쪽은 닫을 때 다시 shutdown하지 않습니다. shutdown_async도 같고, 블로킹하는 대신 close_notify를 기다립니다.
r.unsplit(w)는 한 번의 split에서 나온 두 반쪽으로 연결을 되돌려 줍니다. 두 반쪽은 소비되고, 아무것도 닫거나 shutdown하지 않습니다. 다른 연결의 w를 주면 panic합니다.
let (r, w) = (try await TcpStream::connect_async(addr)).split();
let writer = task::spawn(async {
try! await w.write_all_async(request);
try! await w.close_async(); // 상대는 스트림의 끝을 읽음
0
});
let reply = try await r.read_to_end_async();
try r.close(); // 여기서 소켓이 닫힘
await writer;
#사용 예
use core::task;
use std::net::{tcp_listen, TcpListener, TcpStream};
// blocking: 이 스레드가 accept 와 handle 에서 기다림
using l = try TcpListener::bind("127.0.0.1:8080") {
try for c in l.incoming() {
handle(c); // fn handle(c: TcpStream) 이 c 를 닫음
}
}
// async: 연결마다 task, 기다리는 동안 worker 는 다른 task 실행
async fn serve_all(l: TcpListener) throws (IoError) {
loop {
let (s, _) = try await l.accept_async();
task::spawn(serve(s)); // async fn serve(s: TcpStream)
}
}
#3.2.2. UDP
UDP는 UdpSocket 타입 하나가 모든 역할을 맡습니다. 기본은 데이터그램 송수신입니다. connect로 상대를 고정하면 send / recv만으로 다룰 수 있습니다. 멀티캐스트 가입과 TTL 같은 옵션도 있습니다. QUIC 같은 워크로드를 위해 GSO/GRO용 세그먼트 크기 제어도 있습니다.
struct UdpSocket { /* OS handle */ }
impl UdpSocket {
fn bind<A: ToSocketAddrs>(addr: A) throws (IoError) -> UdpSocket; // 처음으로 bind 되는 주소
fn send_to<B: AsBytes, A: ToSocketAddrs>(self, buf: B, addr: A) throws (IoError) -> usize; // 첫 주소로
fn recv_from(self, buf: SliceMut<u8>) throws (IoError) -> (usize, SocketAddr);
fn connect<A: ToSocketAddrs>(self, addr: A) throws (IoError); // peer 고정: 처음으로 받아 주는 주소
async fn connect_async<A: ToSocketAddrs>(ref self, addr: A) throws (IoError); // 소켓에서 기다리지 않음
fn send<B: AsBytes>(self, buf: B) throws (IoError) -> usize;
fn recv(self, buf: SliceMut<u8>) throws (IoError) -> usize;
// + send_to_async / recv_from_async / send_async / recv_async (ref self)
fn local_addr(self) throws (IoError) -> SocketAddr;
fn peer_addr(self) throws (IoError) -> SocketAddr;
fn set_broadcast(self, on: bool) throws (IoError); // SO_BROADCAST
fn broadcast(self) throws (IoError) -> bool;
fn set_ttl(self, ttl: u32) throws (IoError); // IP_TTL
fn ttl(self) throws (IoError) -> u32;
fn set_read_timeout(self, dur: Duration | none);
fn set_write_timeout(self, dur: Duration | none);
fn read_timeout(self) -> Duration | none;
fn write_timeout(self) -> Duration | none;
fn set_nonblocking(self, nb: bool);
fn try_clone(self) throws (IoError) -> UdpSocket;
fn close(self) throws (IoError); // OS 가 알린 에러를 던짐
// 멀티캐스트 (IPv4)
fn join_multicast_v4(self, addr: Ipv4Addr, interface: Ipv4Addr) throws (IoError);
fn leave_multicast_v4(self, addr: Ipv4Addr, interface: Ipv4Addr) throws (IoError);
fn set_multicast_loop_v4(self, on: bool) throws (IoError);
fn set_multicast_ttl_v4(self, ttl: u32) throws (IoError);
// QUIC 용 (GSO / GRO)
fn set_segment_size(self, size: u16) throws (IoError); // UDP_SEGMENT, Linux 외에는 Unsupported
}
impl io::Close for UdpSocket { ... }
impl io::AsyncClose for UdpSocket { ... }
impl Drop for UdpSocket { ... } // 에러 경로에서 해제
impl From<Socket> for UdpSocket { ... } // datagram Socket (3.2.9)
recv_from / recv는 데이터그램 하나를 buf에 받습니다. buf보다 긴 데이터그램의 나머지는 버려집니다.
#3.2.3. Unix 도메인 소켓
Unix 도메인 소켓은 Unix에만 있으므로 std::os::unix::net에 있습니다(3.10.4). 모양은 여기 TCP 타입과 같습니다.
#3.2.4. SocketAddr / IpAddr
주소 표현의 중심은 IPv4와 IPv6를 합친 SocketAddr enum과, 주소만 담는 같은 합집합 IpAddr입니다. SocketAddrV4 / SocketAddrV6의 필드는 비공개입니다. getter로 읽고 setter(ref self)로 바꿉니다. 복사본은 별개의 값이므로 let b = a; b.set_port(p);는 a를 바꾸지 않습니다. ==는 부분끼리 비교합니다. 문자열 파싱은 FromStr 구현으로 합니다. 호스트 이름의 DNS 조회는 별도 함수가 맡습니다.
enum IpAddr { V4(Ipv4Addr), V6(Ipv6Addr) }
impl IpAddr {
fn is_ipv4(self) -> bool;
fn is_ipv6(self) -> bool;
fn is_loopback(self) -> bool;
}
impl From<Ipv4Addr> for IpAddr { ... }
impl From<Ipv6Addr> for IpAddr { ... }
enum SocketAddr {
V4(SocketAddrV4),
V6(SocketAddrV6),
}
struct SocketAddrV4 { /* ip, port */ }
struct SocketAddrV6 { /* ip, port, flow_info, scope_id */ }
impl SocketAddrV4 {
fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4;
fn ip(self) -> Ipv4Addr;
fn port(self) -> u16;
fn set_ip(ref self, ip: Ipv4Addr);
fn set_port(ref self, port: u16);
}
impl SocketAddrV6 {
fn new(ip: Ipv6Addr, port: u16, flow_info: u32 = 0, scope_id: u32 = 0) -> SocketAddrV6;
fn ip(self) -> Ipv6Addr;
fn port(self) -> u16;
fn flow_info(self) -> u32;
fn scope_id(self) -> u32;
fn set_ip(ref self, ip: Ipv6Addr);
fn set_port(ref self, port: u16);
fn set_flow_info(ref self, flow_info: u32);
fn set_scope_id(ref self, scope_id: u32);
}
impl SocketAddr {
fn new(ip: IpAddr, port: u16) -> SocketAddr; // IPv6: flow_info = scope_id = 0
fn ip(self) -> IpAddr;
fn port(self) -> u16;
fn set_ip(ref self, ip: IpAddr); // 다른 family 면 주소 전체를 바꿈
fn set_port(ref self, port: u16);
fn is_ipv4(self) -> bool;
fn is_ipv6(self) -> bool;
}
impl From<SocketAddrV4> for SocketAddr { ... }
impl From<SocketAddrV6> for SocketAddr { ... }
// 시도할 주소를 차례로 내놓는 것
trait ToSocketAddrs {
fn to_socket_addrs(self) throws (IoError) -> List<SocketAddr>;
}
impl ToSocketAddrs for SocketAddr { ... } // 그 자신
impl ToSocketAddrs for SocketAddrV4 { ... }
impl ToSocketAddrs for SocketAddrV6 { ... }
impl ToSocketAddrs for str { ... } // resolve(self): "host:port", 이름은 조회
impl ToSocketAddrs for (IpAddr, u16) { ... }
impl ToSocketAddrs for List<SocketAddr> { ... } // 순서대로
struct Ipv4Addr { .. } // 비공개 필드
struct Ipv6Addr { .. }
impl Ipv4Addr {
const LOCALHOST: Ipv4Addr; // 127.0.0.1
const UNSPECIFIED: Ipv4Addr; // 0.0.0.0
fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr;
fn octets(self) -> [u8; 4];
fn to_bits(self) -> u32; // big-endian: a.b.c.d 는 a << 24 | ..
fn is_loopback(self) -> bool;
fn is_unspecified(self) -> bool;
fn is_multicast(self) -> bool;
}
impl Ipv6Addr {
const LOCALHOST: Ipv6Addr; // ::1
const UNSPECIFIED: Ipv6Addr; // ::
fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr;
fn segments(self) -> [u16; 8];
fn is_loopback(self) -> bool;
}
// 파싱 / 출력
impl FromStr for SocketAddr { ... } // "127.0.0.1:8080" / "[::1]:8080"; Err = ParseError
impl FromStr for IpAddr { ... } // "127.0.0.1" / "::1"
impl FromStr for Ipv4Addr { ... }
impl FromStr for Ipv6Addr { ... } // "::" 축약 허용
impl Display for SocketAddr { ... } // "127.0.0.1:8080" / "[::1]:8080"; SocketAddrV4 / V6 도
impl Display for IpAddr { ... }
impl Display for Ipv4Addr { ... } // "127.0.0.1"
impl Display for Ipv6Addr { ... } // RFC 5952 형태: "::1"
impl From<u32> for Ipv4Addr { ... }
// 모두 Clone, Copy, PartialEq, Eq, Hash (부분끼리 비교) 를 구현하고,
// Debug 는 Display 와 같게 씀; Ipv4Addr 와 Ipv6Addr 는 PartialOrd, Ord 도 구현
// DNS (getaddrinfo)
fn resolve(host: str) throws (IoError) -> List<SocketAddr>;
resolve는 OS의 getaddrinfo로 주소 목록을 얻고, 호출한 스레드를 막습니다. host는 다음을 받습니다.
host | 결과 |
|---|---|
소켓 주소 ("10.0.0.1:80", "[::1]:80") | 그 주소 하나 (조회 없음) |
"name:port" | name의 주소들, port는 port |
"[v6]:port" | 그 IPv6 주소, port는 port |
| 이름 또는 IP만 | 그 주소들, port 0 |
이름을 찾지 못하면 IoError(NotFound)입니다. 다른 resolver 실패는 Other입니다. 메시지에는 resolver의 설명이 들어갑니다. resolver 실패에는 os_code()가 없습니다(2.23.0). 다만 Windows에서는 resolver가 Winsock 코드를 알리므로 그 코드가 남습니다. 이름과 포트로 첫 주소를 얻으려면 resolve(f"{host}:{port}")[0]을 씁니다(IPv6 host는 [..]로 감쌉니다).
close는 OS가 알린 에러를 던집니다(0.5.9). 이미 닫힌 소켓을 닫는 것은 아무 일도 하지 않습니다. Drop도 소켓을 닫지만, 에러는 버립니다(3.2.0).
#3.2.5. TLS 1.3: net::tls
TLS는 net::tls 하위 모듈에 있고, 처음부터 1.3만 가정합니다. core::crypto 위에 구현했고, 독립적인 감사를 받지 않은 실험 단계 구현입니다(2.21.5). ClientConfig와 ServerConfig가 인증서, 암호 모음, ALPN 프로토콜 목록을 표현합니다. 양자 내성(post-quantum) 옵션으로 ML-KEM 하이브리드 키 교환을 켤 수 있습니다. 둘 다 #[non_exhaustive] 레코드이고, root_certs, cert_chain, private_key를 뺀 공개 필드에는 기본값이 있습니다(6.2.10). 리터럴에는 기본값과 다른 것만 적고, 나중에 더해지는 필드도 모두 기본값을 가집니다. 핸드셰이크 뒤에는 Client / Server가 평문 스트림처럼 동작합니다. 그래서 기존 I/O 코드를 거의 그대로 얹을 수 있습니다.
use std::net::tls;
#[non_exhaustive]
struct ClientConfig {
pub root_certs: List<Certificate>; // 신뢰 앵커 (기본값 없음)
pub cipher_suites: List<CipherSuite> = CipherSuite::all(); // TLS 1.3 suite, 선호 순서
pub alpn_protocols: List<List<u8>> = []; // ["h2", "http/1.1"] 등
pub enable_post_quantum: bool = true; // post-quantum (X25519MLKEM768 hybrid)
pub client_cert_chain: List<Certificate> = []; // 서버가 요청하면 보냄: leaf 먼저; 비면 없음
pub client_key: PrivateKey | none = none; // 클라이언트 leaf 의 키
pub session_cache: SessionCache | none = SessionCache::new(); // resume 할 ticket; none: resume 안 함
pub early_data: List<u8> = []; // 0-RTT 데이터, 아니면 핸드셰이크 뒤의 첫 데이터
}
impl ClientConfig {
fn new() throws (TlsError) -> ClientConfig; // ClientConfig { root_certs: system_roots() }
}
#[non_exhaustive]
struct ServerConfig {
pub cert_chain: List<Certificate>; // leaf 먼저, 그다음 중간 인증서 (기본값 없음)
pub private_key: PrivateKey; // leaf 의 키 (기본값 없음)
pub cipher_suites: List<CipherSuite> = CipherSuite::all();
pub alpn_protocols: List<List<u8>> = [];
pub client_roots: List<Certificate> = []; // 비어 있지 않으면 클라이언트 인증서를 요청하고 이것으로 검증
pub require_client_cert: bool = true; // client_roots 와 함께: 인증서 없는 클라이언트 거부
pub ocsp_response: List<u8> = []; // 요청받으면 staple 하는 DER OCSPResponse; 비면 없음
pub ticket_store: TicketStore | none = TicketStore::new(); // resumption; none: ticket 없음
pub max_early_data: u32 = 0; // 연결마다 받는 0-RTT 바이트; 0: 없음
}
impl ServerConfig {
fn new(cert_chain: List<Certificate>, private_key: PrivateKey) throws (TlsError) -> ServerConfig;
// ServerConfig { cert_chain, private_key } 를 바로 검사: 키는 cert_chain[0] 의 것이어야 함
}
struct SessionCache { .. } // 서버 이름별 클라이언트의 ticket; 복사본은 공유
impl SessionCache {
fn new() -> SessionCache;
fn len(self) -> usize;
fn clear(self);
}
struct TicketStore { .. } // 서버의 resume 가능한 세션; 복사본은 공유
impl TicketStore {
fn new() -> TicketStore;
fn len(self) -> usize;
}
#[non_exhaustive]
enum CipherSuite { Aes128GcmSha256, Aes256GcmSha384, ChaCha20Poly1305Sha256 }
impl CipherSuite {
fn all() -> List<CipherSuite>; // 세 가지 모두, 기본 선호 순서
}
struct Certificate { .. } // Sync: 스레드 사이에서 공유
impl Certificate {
fn from_der<B: AsBytes>(der: B) throws (TlsError) -> Certificate;
fn from_pem(text: str) throws (TlsError) -> List<Certificate>;
fn to_der(self) -> List<u8>; // DER 인코딩의 복사본
fn dns_names(self) -> List<str>;
fn not_before(self) -> SystemTime; // 초 단위 (3.3)
fn not_after(self) -> SystemTime;
}
struct PrivateKey { .. } // Ed25519, ECDSA P-256 / P-384, RSA (2048..4096 bits), RSASSA-PSS
impl PrivateKey {
fn from_der<B: AsBytes>(der: B) throws (TlsError) -> PrivateKey; // PKCS #8
fn from_pem(text: str) throws (TlsError) -> PrivateKey; // PRIVATE KEY, EC PRIVATE KEY 또는 RSA PRIVATE KEY
}
fn system_roots() throws (TlsError) -> List<Certificate>; // OS trust store (호출마다 읽음)
#[non_exhaustive]
enum TlsErrorKind { Io, Certificate, Protocol, PeerAlert }
struct TlsError { .. } // 비공개 필드 (0.5.10); + Display, Debug, Error, PartialEq, Eq, Clone
impl TlsError {
fn new(kind: TlsErrorKind, message: str, alert: u8) -> TlsError;
fn kind(self) -> TlsErrorKind;
fn message(self) -> str; // Display 가 붙이는 "tls: " 없이
fn alert(self) -> u8; // 보낸 alert (PeerAlert 면 받은 것)
}
struct Client { .. }
impl Client {
fn new(stream: TcpStream, server_name: str) throws (TlsError) -> Client;
fn with_config(stream: TcpStream, server_name: str, cfg: ClientConfig) throws (TlsError) -> Client;
async fn new_async(stream: TcpStream, server_name: str) throws (TlsError) -> Client;
async fn with_config_async(stream: TcpStream, server_name: str, cfg: ClientConfig) throws (TlsError) -> Client;
fn close_notify(self) throws (IoError);
fn key_update(self) throws (IoError);
fn close(self) throws (IoError);
async fn close_notify_async(ref self) throws (IoError);
async fn key_update_async(ref self) throws (IoError);
fn negotiated_alpn(self) -> List<u8> | none;
fn peer_certificates(self) -> List<Certificate>;
fn is_resumed(self) -> bool; // 핸드셰이크가 세션을 resume 함
fn is_early_data_accepted(self) -> bool; // early_data 가 0-RTT 데이터로 나감
fn split(self) -> (ReadHalf<Client>, WriteHalf<Client>); // 3.2.1 반쪽으로 나누기
}
impl WriteHalf<Client> { // WriteHalf<Server> 도
fn key_update(self) throws (IoError);
async fn key_update_async(ref self) throws (IoError);
}
struct Server { .. }
impl Server {
fn new(stream: TcpStream, cfg: ServerConfig) throws (TlsError) -> Server;
async fn new_async(stream: TcpStream, cfg: ServerConfig) throws (TlsError) -> Server;
// close_notify, key_update, close, 그 *_async 형태,
// negotiated_alpn, peer_certificates, split 은 Client 와 같고, 추가로:
fn server_name(self) -> str | none; // 클라이언트의 SNI
fn is_resumed(self) -> bool;
fn early_data(self) -> List<u8>; // 받아들인 0-RTT 데이터; read 는 그 뒤의 것을 돌려줌
}
Client와 Server는 io::Read, io::Write, io::AsyncRead, io::AsyncWrite(2.23), io::Close(아래의 close. 소유자가 하나하나 닫습니다, 3.2.0), Drop(에러 경로에서 같은 일을 하고 에러는 버림)을 구현합니다. 실패한 핸드셰이크는 받은 스트림을 닫고, 성공한 핸드셰이크는 그 스트림을 가집니다. 연결은 affine입니다(2.13.4). let b = c는 연결을 옮기고, 한 연결은 한 번에 한 스레드만 씁니다(!Sync). 읽기와 쓰기를 동시에 하려면 split으로 나눕니다(3.2.1). 읽기 반쪽이 읽는 동안 쓰기 반쪽이 씁니다. 두 반쪽은 서로 다른 스레드나 task에서 쓸 수 있습니다. 쓰기 반쪽을 닫으면 close_notify를 보낸 뒤 소켓의 쓰기 방향을 shutdown합니다. Certificate는 Sync입니다.
레코드는 만들어진 순서대로 나갑니다. 읽기가 받은 KeyUpdate 요청에는 연결의 다음 레코드로 답합니다. 진행 중인 쓰기가 없으면 바로, 있으면 그 쓰기의 레코드 바로 뒤에 답하므로, 읽기는 가득 찬 소켓에 막힌 쓰기를 기다리지 않습니다. close_notify를 보낸 뒤에는 KeyUpdate 요청에 답하지 않습니다(close_notify 뒤에는 아무것도 보내지 않음).
*_async 메서드는 3.2.0을 따릅니다. 소켓이 준비되지 않은 동안 task만 중단합니다. 핸드셰이크(new_async, with_config_async)도 상대 메시지를 기다리는 동안 마찬가지입니다. 한 연결에서 블로킹 형태와 async 형태를 섞어 써도 됩니다.
스택은 구현이 제공하고, core::crypto(2.21) 위에 Nabi로 작성합니다. OS나 서드파티 TLS 라이브러리는 쓰지 않습니다. 사용자가 그런 라이브러리를 호출할 일도 없습니다. TLS 1.3(RFC 8446)만 쓰고, TLS 1.2 이하는 거부합니다. 핸드셰이크가 지원하는 기능은 다음과 같습니다. X25519와 X25519MLKEM768 하이브리드(ML-KEM-768 + X25519, enable_post_quantum), HelloRetryRequest(group 또는 cookie), ALPN, SNI, KeyUpdate, close_notify, 클라이언트 인증서, OCSP stapling, 0-RTT 데이터를 포함한 재개(resumption)입니다.
재개: ticket_store가 있는 서버는 핸드셰이크마다 NewSessionTicket 하나를 보냅니다. store는 세션을 보관합니다(최대 4096개, 가장 오래된 것부터 버림, 수명 2시간). ticket 하나는 많아야 한 번 씁니다. session_cache가 있는 클라이언트는 받은 ticket을 접속한 서버 이름 아래에 보관합니다(최대 64개). 그리고 살아 있는 ticket 가운데 가장 새 ticket을 한 번 제시합니다. 단, 그 ticket의 cipher suite 해시를 클라이언트도 제시할 때만입니다. psk_dhe_ke만 쓰므로 재개한 핸드셰이크도 새로 키 교환을 합니다. 재개한 연결은 인증서 인증을 건너뜁니다. peer_certificates()는 원래 연결의 chain을 돌려줍니다. 클라이언트는 읽는 동안 ticket을 받습니다.
0-RTT: early_data가 비어 있지 않고 ticket이 그만큼의 바이트를 허용하면, 클라이언트는 그 데이터를 ClientHello와 함께 early data로 보냅니다. 그렇지 않거나 서버가 거절하면 핸드셰이크 뒤 첫 application data로 보냅니다. 어느 쪽인지는 is_early_data_accepted()가 알려 줍니다. 서버는 다음 조건을 모두 만족할 때만 early data를 받습니다. max_early_data > 0이고, 첫 번째로 제시된 ticket이고, HelloRetryRequest가 없고, ticket의 cipher suite와 ALPN 프로토콜이 같고, 클라이언트의 ticket age가 서버의 값과 10초 이내여야 합니다. 받은 데이터는 early_data()로 내주고, 거절한 early data는 건너뜁니다. 모든 ticket은 그 TicketStore에서 한 번만 쓰입니다. 그래서 재전송된 ClientHello는 아무것도 재개하지 못하고, 그 early data는 건너뜁니다(RFC 8446 8.1). 서로의 재전송을 거부해야 하는 서버는 store 하나를 함께 써야 합니다. early data는 여전히 ticket에 대해 forward secrecy가 없으므로 멱등이기를 권장합니다.
클라이언트 인증서: client_roots가 비어 있지 않은 서버는 CertificateRequest를 보냅니다. 서버는 클라이언트의 chain을 서버 chain처럼(아래) client_roots에 대해 검증합니다. 이때 extendedKeyUsage clientAuth를 요구하고, 이름은 검사하지 않습니다. 그 CertificateVerify도 검사합니다. 인증서가 없는 클라이언트는 require_client_cert이면 certificate_required로 핸드셰이크가 실패합니다. 아니면 peer_certificates() 없이 계속합니다. 서버가 client_key에 맞는 scheme을 받아들이면, 클라이언트는 CertificateRequest에 client_cert_chain과 client_key로 만든 CertificateVerify로 답합니다. 그렇지 않으면 빈 Certificate로 답합니다. client_key가 첫 인증서의 키가 아니면 아무것도 보내기 전에 Client::with_config가 실패합니다.
서버 인증: 인증서 경로는 상대의 chain에서 root_certs 중 하나까지 구성합니다. 그리고 RFC 5280에 따라 검증합니다. 검증 항목은 서명, 현재 시각 기준 유효 기간, basicConstraints, keyUsage, extendedKeyUsage serverAuth, DNS 및 IP name constraints입니다. 모르는 critical extension이 있으면 실패합니다. 서버 이름은 subjectAltName과만 대조합니다(RFC 6125: 대소문자 무시, wildcard는 가장 왼쪽 label 전체). IP 리터럴은 iPAddress 항목과 대조하고, SNI를 보내지 않습니다.
허용하는 서명은 다음과 같습니다.
- Ed25519
- SHA-256/384/512를 쓰는 ECDSA P-256 / P-384
- RSA PKCS #1 v1.5(인증서에만)
- SHA-256/384/512를 쓰는 RSA-PSS(2048~4096비트 키, rsaEncryption 또는 id-RSASSA-PSS). 인증서에서는 salt 길이와 관계없이 받고, id-RSASSA-PSS 키의 해시와 최소 salt를 따릅니다.
폐기(revocation) 확인: 클라이언트는 OCSP 응답을 요청합니다(status_request). stapling으로 받은 응답은 다음 조건을 모두 만족해야 합니다. 성공한 basic OCSP 응답(RFC 6960)이어야 합니다. leaf의 발급자, 또는 발급자가 extendedKeyUsage OCSPSigning으로 발급한 인증서가 서명해야 합니다. leaf를 가리키는 SHA-1 또는 SHA-2 CertID가 있어야 합니다. thisUpdate가 5분 넘게 앞서면 안 됩니다. nextUpdate가 있고, 그 시각이 지나지 않아야 합니다. 상태가 revoked이면 certificate_revoked로 실패합니다. 그 밖의 문제(unknown 상태 포함)는 bad_certificate_status_response로 실패합니다. status_request에 대한 TLS feature extension(RFC 7633)이 있는 leaf는 stapling 응답을 요구합니다. staple도 그 extension도 없으면 인증서를 받아들입니다. CRL과 네트워크 OCSP 조회는 쓰지 않습니다.
인증서 실패는 원인에 따라 alert가 다릅니다. 만료되었거나 아직 유효하지 않은 인증서는 certificate_expired입니다. extendedKeyUsage가 그 역할을 허용하지 않는 인증서는 unsupported_certificate입니다. root_certs까지의 경로가 없는 인증서는 unknown_ca입니다. 그 밖의 실패는 bad_certificate입니다. ServerHello, HelloRetryRequest, EncryptedExtensions 또는 Certificate 항목에 클라이언트가 요청하지 않은 extension이 있으면 unsupported_extension으로 실패합니다. 실패한 핸드셰이크는 그 alert를 보낸 뒤 스트림을 닫습니다.
양쪽 모두 CertificateVerify를 키의 scheme으로 서명합니다. scheme은 ed25519, ecdsa_secp256r1_sha256, ecdsa_secp384r1_sha384입니다. rsaEncryption 인증서는 상대가 제시한 rsa_pss_rsae_sha256 / _sha384 / _sha512 중 첫 번째를 씁니다. id-RSASSA-PSS 인증서는 상대가 제시한 rsa_pss_pss_sha256 / _sha384 / _sha512 중 키의 매개변수가 허용하는 첫 번째를 씁니다. PrivateKey는 PKCS #8(Ed25519, P-256 / P-384의 id-ecPublicKey, rsaEncryption, id-RSASSA-PSS), RFC 5915 EC PRIVATE KEY, PKCS #1 RSA PRIVATE KEY를 읽습니다. ServerConfig::new, Server::new, Server::new_async는 cert_chain이 비었거나 키의 공개 부분이 leaf의 공개 키가 아니면 실패합니다(TlsErrorKind::Certificate).
스택은 traffic, handshake, resumption secret, record 키, 키 교환 secret, ticket PSK, Ed25519 / EC 개인 키를 비밀 저장소(2.21.5)에 둡니다. 그리고 KeyUpdate 때, 핸드셰이크가 끝날 때, 닫을 때 지웁니다.
ClientConfig::new()는 OS trust store를 읽을 수 없으면(store를 찾지 못함, 읽을 수 없는 bundle, 모든 wasm 타깃) system_roots() 에러를 던집니다. Client::new와 Client::new_async도 이 함수로 config를 만들므로 같은 에러를 던집니다. 다른 필드는 struct update로 정합니다: ClientConfig { alpn_protocols: [..], ..try ClientConfig::new() }. store가 없으면 root_certs를 넣은 리터럴로 만듭니다: ClientConfig { root_certs: roots }.
Client::close와 Server::close는 연결이 건강하면 close_notify를 보내고(그 실패는 알리지 않습니다), 소켓을 닫으며 OS가 알린 에러를 던집니다. 키는 어느 경우에나 지웁니다.
system_roots()는 OS trust store를 읽습니다. macOS keychain의 anchor(와 무조건 신뢰된 admin / user 인증서), Windows ROOT store, Linux에서 처음 발견되는 CA bundle(/etc/ssl/certs/ca-certificates.crt, /etc/pki/tls/certs/ca-bundle.crt 등), Android의 루트 인증서(Android 14부터는 /apex/com.android.conscrypt/cacerts, 그 전에는 /system/etc/security/cacerts)입니다. SSL_CERT_FILE이 있으면 이 값을 덮어씁니다. wasm 타깃에는 store가 없으므로 root_certs를 넘겨야 합니다.
read는 상대의 close_notify 뒤에 0을 돌려줍니다. close_notify 없이 끝난 연결은 IoError(UnexpectedEof)입니다. 프로토콜 실패는 fatal alert를 보낸 뒤 IoError(InvalidData)입니다. TLS record는 통째로 쓰이므로 write는 buf 전체를 씁니다.
#사용 예
사용법은 단순합니다. 평문 TCP 연결 위에 TLS 클라이언트를 얹고, 그 위에서 평문 I/O를 호출합니다.
use std::net::{tcp_connect, tls};
let conn = try tcp_connect("example.com:443");
let tls_conn = try tls::Client::new(conn, "example.com");
try tls_conn.write_all(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
let resp = try tls_conn.read_to_end();
try tls_conn.close(); // close_notify 뒤 소켓을 닫음
#3.2.6. 편의 함수
흔한 경우를 위해 타입별 생성자를 자유 함수로도 둡니다. 같은 ToSocketAddrs(3.2.4)를 받으므로 tcp_connect("example.com:80")처럼 호스트 이름을 그대로 넘길 수 있습니다.
fn tcp_connect<A: ToSocketAddrs>(addr: A) throws (IoError) -> TcpStream; // TcpStream::connect(addr)
async fn tcp_connect_async<A: ToSocketAddrs>(addr: A) throws (IoError) -> TcpStream; // TcpStream::connect_async(addr)
fn tcp_listen<A: ToSocketAddrs>(addr: A) throws (IoError) -> TcpListener; // TcpListener::bind(addr)
fn udp_bind<A: ToSocketAddrs>(addr: A) throws (IoError) -> UdpSocket; // UdpSocket::bind(addr)
connect는 주소를 차례로 시도해 처음 연결되는 것을 돌려주고, bind는 처음으로 되는 주소에 바인드합니다. 모두 실패하면 마지막 에러를 던지고, 주소 목록이 비면 InvalidInput입니다.
#3.2.7. zerocopy 훅(고급)
sendfile, splice, write_zerocopy는 Linux에만 있으므로 std::os::linux::net의 트레잇 TcpStreamExt입니다(3.10.6). Linux에서는 prelude에 있어 stream.sendfile(ref f, 0, n)에 use가 필요 없습니다. 소켓의 OS 디스크립터는 AsRawFd(unix)나 AsRawSocket(Windows)으로 얻습니다(3.10.2).
#3.2.8. 모듈 매핑
플랫폼별 지원 범위는 다음과 같습니다. 핵심 기능은 데스크톱 OS와 wasi 양쪽에서 동작합니다. 하지만 Unix 소켓이나 zerocopy hook처럼 Linux 고유 기능에 의존하는 항목은 일부 플랫폼에서만 켜집니다.
| 항목 | linux/macos/windows | wasi | 비고 |
|---|---|---|---|
| TCP | ✓ | ✓ | wasi:sockets |
| UDP | ✓ | ✓ | wasi:sockets |
| Unix 소켓 | linux/macos | ✗ | os::unix::net. Windows 형태 없음 (named pipe 별도) |
| TLS 1.3 | ✓ | ✓ (trust store 없음: root_certs 전달) | Nabi 자체 구현, core::crypto 위 |
| sendfile | linux | ✗ | os::linux::net::TcpStreamExt |
| splice | linux | ✗ | os::linux::net::TcpStreamExt |
| MSG_ZEROCOPY | linux 4.14+ | ✗ | os::linux::net::TcpStreamExt |
Socket | ✓ | wasip2 | SocketType::Raw와 set_reuse_port는 Windows와 WASI에 없음 |
#3.2.9. Socket: 저수준 층
Socket은 운영체제가 가진 그대로의 소켓이고, Rust socket2의 모양을 따릅니다. 도메인, 타입, 프로토콜과 옵션 하나하나를 호출자가 정하고, 각 메서드는 이름 그대로의 시스템 호출 하나입니다. bind는 SO_REUSEADDR를 켜지 않고, connect는 이름을 조회하지 않으며, listen은 backlog를 받습니다. 준비가 끝나면 TcpStream::from(s), TcpListener::from(s), UdpSocket::from(s)가 소켓을 넘겨받고(s는 이동합니다), Socket::from이 반대 방향입니다.
#[non_exhaustive]
enum Domain { Ipv4, Ipv6 } // AF_INET, AF_INET6; Clone, Copy, PartialEq, Eq, Hash, Debug
impl Domain {
fn for_address(addr: SocketAddr) -> Domain;
}
#[non_exhaustive]
enum SocketType { Stream, Datagram, Raw } // SOCK_STREAM, SOCK_DGRAM, SOCK_RAW; Clone, Copy, PartialEq, Eq, Hash, Debug
struct Protocol { /* IP 프로토콜 번호 */ } // Clone, Copy, PartialEq, Eq, Hash, Debug
impl Protocol {
const ICMPV4: Protocol; // 1
const TCP: Protocol; // 6
const UDP: Protocol; // 17
const ICMPV6: Protocol; // 58
fn new(number: i32) -> Protocol;
fn number(self) -> i32;
}
struct Socket { /* OS handle */ } // Debug 는 `Socket` 을 출력
impl Socket {
fn new(domain: Domain, ty: SocketType, protocol: Protocol | none = none) throws (IoError) -> Socket;
// none: 그 타입의 기본 프로토콜
fn bind(self, addr: SocketAddr) throws (IoError);
fn listen(self, backlog: i32) throws (IoError);
fn connect(self, addr: SocketAddr) throws (IoError); // non-blocking 이면 진행 중일 때 WouldBlock
fn connect_timeout(self, addr: SocketAddr, dur: Duration) throws (IoError);
async fn connect_async(ref self, addr: SocketAddr) throws (IoError);
fn accept(self) throws (IoError) -> (Socket, SocketAddr);
async fn accept_async(ref self) throws (IoError) -> (Socket, SocketAddr);
fn local_addr(self) throws (IoError) -> SocketAddr;
fn peer_addr(self) throws (IoError) -> SocketAddr;
fn shutdown(self, how: Shutdown) throws (IoError);
async fn shutdown_async(ref self, how: Shutdown) throws (IoError);
fn send_to<B: AsBytes>(self, buf: B, addr: SocketAddr) throws (IoError) -> usize;
fn recv_from(self, buf: SliceMut<u8>) throws (IoError) -> (usize, SocketAddr);
// + send_to_async / recv_from_async (ref self)
// 옵션: setter 마다 같은 이름의 getter 가 있음 (set_keepalive, set_nonblocking 은 제외)
fn set_reuse_address(self, on: bool) throws (IoError); // SO_REUSEADDR
fn set_reuse_port(self, on: bool) throws (IoError); // SO_REUSEPORT; Unix 밖에서는 Unsupported
fn set_nodelay(self, on: bool) throws (IoError); // TCP_NODELAY
fn set_broadcast(self, on: bool) throws (IoError); // SO_BROADCAST
fn set_recv_buffer_size(self, size: usize) throws (IoError); // SO_RCVBUF (OS 가 맞춰 바꿀 수 있음)
fn set_send_buffer_size(self, size: usize) throws (IoError); // SO_SNDBUF
fn set_ttl(self, ttl: u32) throws (IoError); // IP_TTL
fn set_only_v6(self, on: bool) throws (IoError); // IPV6_V6ONLY
fn set_linger(self, dur: Duration | none) throws (IoError); // SO_LINGER, 초 단위; none: 끔
fn set_keepalive(self, alive: Duration | none) throws (IoError); // TcpStream 과 같음 (getter 없음)
fn set_nonblocking(self, nb: bool);
fn set_read_timeout(self, dur: Duration | none);
fn set_write_timeout(self, dur: Duration | none);
fn read_timeout(self) -> Duration | none;
fn write_timeout(self) -> Duration | none;
fn try_clone(self) throws (IoError) -> Socket;
fn close(self) throws (IoError);
}
impl io::Read for Socket { ... } // io::Write, io::AsyncRead, io::AsyncWrite 도
impl io::Close for Socket { ... }
impl Drop for Socket { ... } // 에러 경로에서 해제
impl From<TcpStream> for Socket { ... } // TcpListener, UdpSocket 도
새 소켓은 이 모듈의 다른 소켓처럼 내부적으로 non-blocking이고 자식 프로세스에 상속되지 않습니다. 블로킹 호출은 3.2.0대로 기다립니다.
use std::net::{Socket, Domain, SocketType, Protocol, TcpListener};
let s = try Socket::new(Domain::Ipv6, SocketType::Stream, Protocol::TCP);
try s.set_only_v6(false); // 한 소켓으로 IPv4 도
try s.set_reuse_address(true);
try s.bind(try "[::]:8080".parse());
try s.listen(1024);
let l = TcpListener::from(s);
잘못된 곳이 있나요? GitHub에서 이 페이지 고치기. 마지막 수정