diff --git a/vlib/net/socket.v b/vlib/net/socket.v index ecc6bd87f8..0510dfc83c 100644 --- a/vlib/net/socket.v +++ b/vlib/net/socket.v @@ -13,6 +13,8 @@ import const ( AF_INET6 AF_UNSPEC SOCK_STREAM + SOCK_DGRAM + IPPROTO_UDP SOL_SOCKET SO_REUSEADDR SO_REUSEPORT @@ -95,6 +97,10 @@ pub fn socket(family int, _type int, proto int) ?Socket { return s } +pub fn socket_udp() ?Socket { + return socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) +} + // set socket options pub fn (s Socket) setsockopt(level int, optname int, optvalue *int) ?int { res := C.setsockopt(s.sockfd, level, optname, optvalue, C.sizeof(optvalue)) @@ -111,11 +117,11 @@ pub fn (s Socket) bind(port int) ?int { addr.sin_port = C.htons(port) addr.sin_addr.s_addr = C.htonl(INADDR_ANY) size := 16 // sizeof(C.sockaddr_in) - res := C.bind(s.sockfd, &addr, size) + res := int(C.bind(s.sockfd, &addr, size)) if res < 0 { return error('socket: bind failed') } - return int(res) + return res } // put socket into passive mode and wait to receive @@ -235,6 +241,8 @@ pub fn (s Socket) recv(bufsize int) byteptr { pub fn (s Socket) cread( buffer byteptr, buffersize int ) int { return int( C.read(s.sockfd, buffer, buffersize) ) } +// Receive a message from the socket, and place it in a preallocated buffer buf, +// with maximum message size bufsize. Returns the length of the received message. pub fn (s Socket) crecv( buffer byteptr, buffersize int ) int { return int( C.recv(s.sockfd, buffer, buffersize, 0) ) } diff --git a/vlib/net/socket_udp_test.v b/vlib/net/socket_udp_test.v new file mode 100644 index 0000000000..f28c55c1d2 --- /dev/null +++ b/vlib/net/socket_udp_test.v @@ -0,0 +1,18 @@ +import net + +fn start_socket_udp_server() { + bufsize := 1024 + bytes := [1024]byte + s := net.socket_udp() or { panic(err) } + _ := s.bind( 9876 ) or { panic(err) } + println('Waiting for udp packets:') + for { + res := s.crecv(bytes, bufsize) + if res < 0 { break } + print('Received $res bytes: ' + tos(bytes, res)) + } +} + +fn test_udp_server() { + // start_socket_udp_server() +}