From b10b21900348dbcd95846d2c30af5a558daa4607 Mon Sep 17 00:00:00 2001 From: Quentin Date: Thu, 9 Jul 2020 12:51:53 +0200 Subject: [PATCH] WIP network bindings --- bindings/libc.scm | 23 +++++++++++++++++++---- examples/udp_server.scm | 29 ++++++++++++++++++++++++++--- 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/bindings/libc.scm b/bindings/libc.scm index 85dc570..00e753a 100644 --- a/bindings/libc.scm +++ b/bindings/libc.scm @@ -55,10 +55,19 @@ ((SO_REUSEADDR) #x2) )) -(define (alloc size fx) - (let ([v (foreign-alloc size)]) - (fx v) - (foreign-free v))) +(define (inet_pton af src dst) + ((foreign-procedure + "inet_pton" + (int string void*) + int) + (domain->int af) + src dst)) + +; htons +(define (htons host) + ((foreign-procedure + "htons" + ( (define (setsockopt sockfd level optname optval optlen) ((foreign-procedure @@ -70,4 +79,10 @@ (optname->int optname) optval optlen)) +(define (bind sockfd address address_len) + ((foreign-procedure + "bind" + (int void* int) + int) sockfd address address_len)) + diff --git a/examples/udp_server.scm b/examples/udp_server.scm index 0ab5afc..16648ac 100644 --- a/examples/udp_server.scm +++ b/examples/udp_server.scm @@ -7,6 +7,11 @@ (raise msg)) (#t ret))) +(define (alloc size fx) + (let ([v (foreign-alloc size)]) + (fx v) + (foreign-free v))) + (define (udpsock-create fx) (fx (check-err @@ -27,7 +32,25 @@ (ftype-sizeof int)) "Unable to set REUSE ADDRESS")))) +(define (udpsock-bind sock addr port) + (alloc + (ftype-sizeof sockaddr_in) + (lambda (addr) + (ftype-set! sockaddr_in (sin_family) addr (domain->int 'AF_INET)) + (ftype-set! sockaddr_in (sin_port) addr (htons port)) + (check-err + (inet_pton + 'AF_INET + addr + (ftype-&ref sockaddr_in (sin_addr) addr)) + "Unable to convert your IP address to binary") + (bind + sock + addr + (ftype-sizeof addr))))) + (udpsock-create - (lambda (s) - (udpsock-reuseaddr s) - (printf "~a~%" s))) + (lambda (sock) + (udpsock-reuseaddr sock) + (udpsock-bind sock "0.0.0.0" 1337) + (printf "~a~%" sock)))