This commit is contained in:
ge
2026-04-04 00:47:35 +03:00
parent 4e43912583
commit 1cf6d878b5
19 changed files with 438 additions and 302 deletions
+35 -10
View File
@@ -3,20 +3,23 @@ module netio
import os
#include <sys/socket.h>
#include <netinet/in.h>
fn C.socket(i32, i32, i32) i32
fn C.bind(i32, voidptr, i32) i32
fn C.connect(i32, voidptr, i32) i32
fn C.listen(i32, i32) i32
fn C.accept(i32, voidptr, i32) i32
fn C.accept(i32, voidptr, voidptr) i32
fn C.shutdown(i32, i32) i32
fn C.close(i32) i32
fn C.setsockopt(i32, i32, i32, voidptr, i32) i32
fn C.getsockopt(i32, i32, i32, voidptr, i32) i32
struct C.sockaddr_storage {}
pub struct Socket {
pub:
fd int
fd int = -1
}
// Socket.new creates new socket.
@@ -32,6 +35,11 @@ pub fn Socket.new(domain AddrFamily, typ SocketType, protocol Protocol) !Socket
}
}
// typeof reports the actual socket type.
pub fn (s Socket) typeof() !SocketType {
return s.get_option_int(C.SOL_SOCKET, C.SO_TYPE)!
}
// Socket shutdown modes. See [shutdown(3p)](https://man7.org/linux/man-pages/man3/shutdown.3p.html) for details.
pub enum Shutdown {
read = C.SHUT_RD
@@ -61,21 +69,38 @@ pub fn (s Socket) listen(backlog int) ! {
}
// accept accepts a new connection on a socket.
pub fn (s Socket) accept() !Socket {
new_fd := C.accept(s.fd, 0, 0)
if new_fd == -1 {
// The return values are the new socket connected to remote and the remote socket address.
pub fn (s Socket) accept() !(Socket, SocketAddr) {
mut sock_addr_storage := &C.sockaddr_storage{}
mut sock_addr_len := sizeof(C.sockaddr_storage)
fd := C.accept(s.fd, sock_addr_storage, &sock_addr_len)
if fd == -1 {
return os.last_error()
}
return Socket{
fd: new_fd
sock := Socket{
fd: fd
}
sock_addr := unsafe {
SocketAddr.from_ptr(sock_addr_storage, sock_addr_len)!
}
return sock, sock_addr
}
// set_option sets the socket option.
pub fn (s Socket) set_option(level SocketLevel, option SocketOption, value int) ! {}
pub fn (s Socket) set_option(level SocketLevel, option SocketOption, value int) ! {
if C.setsockopt(s.fd, i32(level), i32(option), i32(value), sizeof(value)) == -1 {
return os.last_error()
}
}
// get_option gets the socket option.
pub fn (s Socket) get_option(level SocketLevel, option SocketOption) ! {}
// get_option gets the socket option as int.
pub fn (s Socket) get_option_int(level SocketLevel, option SocketOption) !int {
mut result := 0
if C.getsockopt(s.fd, i32(level), i32(option), &result, sizeof(result)) == -1 {
return os.last_error()
}
return result
}
// shutdown shut downs socket send and receive operations.
pub fn (s Socket) shutdown(how Shutdown) ! {