Add basic UDP message receiving

This commit is contained in:
Sofia 2025-08-28 23:37:47 +03:00
commit 6196d41c93
4 changed files with 127 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

23
Cargo.lock generated Normal file
View File

@ -0,0 +1,23 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "libc"
version = "0.2.175"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a82ae493e598baaea5209805c49bbf2ea7de956d50d7da0da1164f9c6d28543"
[[package]]
name = "panic-halt"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a513e167849a384b7f9b746e517604398518590a9142f4846a32e3c2a4de7b11"
[[package]]
name = "udp-tests"
version = "0.1.0"
dependencies = [
"libc",
"panic-halt",
]

14
Cargo.toml Normal file
View File

@ -0,0 +1,14 @@
[package]
name = "udp-tests"
version = "0.1.0"
edition = "2024"
[dependencies]
libc = { version = "0.2.175", default-features = false }
panic-halt = "1.0.0"
[profile.dev]
panic = "abort"
[build]
rustflags = ["-C", "link-args=-lc"]

89
src/main.rs Normal file
View File

@ -0,0 +1,89 @@
#![no_std]
#![no_main]
use core::{
alloc::{GlobalAlloc, Layout},
ffi::CStr,
ptr::null_mut,
};
extern crate alloc;
use alloc::vec::Vec;
use panic_halt as _;
fn handle_error(code: i32, err: &'static core::ffi::CStr) {
unsafe {
if code == -1 {
libc::perror(err.as_ptr());
libc::exit(libc::EXIT_FAILURE);
}
}
}
struct MyAllocator;
unsafe impl GlobalAlloc for MyAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
unsafe { libc::malloc(layout.size()) as *mut u8 }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { libc::free(ptr as *mut libc::c_void) }
}
}
#[global_allocator]
static GLOBAL: MyAllocator = MyAllocator;
#[unsafe(no_mangle)]
pub extern "C" fn main(_argc: isize, _argv: *const *const u8) -> isize {
// Since we are passing a C string the final null character is mandatory
unsafe {
libc::printf(c"Hello world!\n".as_ptr());
let socket = libc::socket(libc::AF_INET, libc::SOCK_DGRAM, libc::IPPROTO_UDP);
let address = libc::sockaddr_in {
sin_family: libc::AF_INET as u16,
sin_port: libc::htons(8080),
sin_addr: libc::in_addr {
s_addr: libc::INADDR_ANY,
},
sin_zero: [0, 0, 0, 0, 0, 0, 0, 0],
};
handle_error(
libc::bind(
socket,
&raw const address as *const libc::sockaddr,
core::mem::size_of::<libc::sockaddr_in>() as u32,
),
c"bind",
);
let mut otus = Vec::with_capacity(10);
loop {
let buf = libc::malloc(16) as *mut u8;
let mut other = libc::malloc(core::mem::size_of::<libc::sockaddr_in>());
let mut other_size = 0;
libc::recvfrom(
socket,
buf as *mut libc::c_void,
1,
0,
&raw mut other as *mut libc::sockaddr,
&mut other_size,
);
otus.push(*buf);
libc::printf(c"Data: %s\n".as_ptr(), buf);
libc::free(buf as *mut libc::c_void);
}
}
0
}