1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

net: add udp socket support and a simple udp server example.

This commit is contained in:
Delyan Angelov
2019-08-20 21:52:58 +03:00
committed by Alexander Medvednikov
parent 51818346df
commit ffb6c6f5b4
2 changed files with 28 additions and 2 deletions

View File

@ -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) )
}