Last active
March 7, 2025 09:55
-
-
Save Jipok/49b86b4488aa0b7ee0d8454139f44e73 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
#flag -I/usr/include | |
#include <sys/socket.h> | |
#include <sys/un.h> | |
#include <unistd.h> | |
#include <string.h> | |
// Объявляем необходимые C функции и структуру | |
fn C.socket(domain int, type_ int, protocol int) int | |
fn C.bind(sockfd int, addr &C.sockaddr_un, addrlen int) int | |
fn C.recv(sockfd int, buf &u8, len int, flags int) int | |
fn C.close(fd int) int | |
fn C.perror(s &char) | |
struct C.sockaddr_un { | |
sun_family u16 | |
sun_path [108]char | |
} | |
// Константы для Unix-сокетов | |
const af_unix = 1 | |
const sock_dgram = 2 | |
fn main() { | |
// Создаем Unix domain datagram сокет. | |
fd := C.socket(af_unix, sock_dgram, 0) | |
if fd == -1 { | |
println('Error: cannot create socket') | |
return | |
} | |
// Подготавливаем адрес для /dev/log | |
mut addr := C.sockaddr_un{} | |
addr.sun_family = u16(af_unix) | |
log_path := '/dev/log' | |
path_bytes := log_path.bytes() | |
// Копируем log_path в массив sun_path по байтам (без unsafe-блоков) | |
for i, b in path_bytes { | |
if i >= addr.sun_path.len { | |
break | |
} | |
addr.sun_path[i] = b | |
} | |
// Обеспечиваем нулевое завершение строки, если это возможно | |
if path_bytes.len < addr.sun_path.len { | |
addr.sun_path[path_bytes.len] = 0 | |
} | |
// Удаляем существующий файл сокета, если он имеется | |
if os.exists(log_path) { | |
os.rm(log_path) or { println('Warning: failed to remove existing socket file') } | |
} | |
// Привязываем сокет к /dev/log | |
ret := C.bind(fd, &addr, int(sizeof(addr))) | |
if ret == -1 { | |
println('Error: cannot bind to /dev/log') | |
C.perror(c'bind error') | |
C.close(fd) | |
return | |
} | |
println('Listening on /dev/log for new packages...') | |
// Цикл приема входящих датаграмм | |
for { | |
mut buffer := [1024]u8{} | |
n := C.recv(fd, &buffer[0], buffer.len, 0) | |
if n > 0 { | |
println('New packet received, size: ${n}') | |
// Преобразуем полученные байты в строку | |
msg := buffer[0..n].bytestr() | |
println('Packet content: ${msg}') | |
} else if n == 0 { | |
// Данных не получено – продолжаем слушать | |
continue | |
} else { | |
// Произошла ошибка при чтении | |
println('Error reading from socket') | |
break | |
} | |
} | |
C.close(fd) | |
// Удаляем файл сокета после завершения работы | |
if os.exists(log_path) { | |
os.rm(log_path) or { println('Warning: failed to remove socket file') } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment