net: clean up

pull/1049/head
Alexander Medvednikov 2019-06-30 21:00:22 +02:00
parent 6a1b16c72c
commit fde0e39abf
2 changed files with 32 additions and 32 deletions

View File

@ -102,39 +102,39 @@ fn dial(addr string, port int) Conn {
fn listen(addr string, port int) Listener { fn listen(addr string, port int) Listener {
mut hints := C.addrinfo{} mut hints := C.addrinfo{}
res := &C.addrinfo{!} res := &C.addrinfo{!}
new_fd := 0 new_fd := 0
BACKLOG := 10 BACKLOG := 10
strport := port.str() strport := port.str()
option := 1 option := 1
listener := C.socket(PF_INET, SOCK_STREAM, 0) listener := C.socket(PF_INET, SOCK_STREAM, 0)
C.setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(int)) C.setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(int))
bad_listener := Listener{their_addr: 0} bad_listener := Listener{their_addr: 0}
if listener < 0 { if listener < 0 {
println('couldnt create listen scoket') println('couldnt create listen scoket')
return bad_listener return bad_listener
} }
// socket address used for the server // socket address used for the server
mut server_address := C.sockaddr_in{} mut server_address := C.sockaddr_in{}
server_address.sin_family = AF_INET server_address.sin_family = AF_INET
// htons: host to network short: transforms a value in host byte // htons: host to network short: transforms a value in host byte
// ordering format to a short value in network byte ordering format // ordering format to a short value in network byte ordering format
server_address.sin_port = C.htons(port) server_address.sin_port = C.htons(port)
// htonl: host to network long: same as htons but to long // htonl: host to network long: same as htons but to long
server_address.sin_addr.s_addr = C.htonl(INADDR_ANY) server_address.sin_addr.s_addr = C.htonl(INADDR_ANY)
// size := sizeof(C.sockaddr_in) // 16 size := 16 // sizeof(C.sockaddr_in)
if C.bind(listener, &server_address, 16) < 0 { if C.bind(listener, &server_address, size) < 0 {
println('cant bind') println('cant bind')
return bad_listener return bad_listener
} }
if C.listen(listener, BACKLOG) < 0 { if C.listen(listener, BACKLOG) < 0 {
println('cant listen') println('cant listen')
return bad_listener return bad_listener
} }
l := Listener { l := Listener {
listener: listener, listener: listener,
their_addr: 0 their_addr: 0
} }
return l return l
} }
// accept an incoming connection // accept an incoming connection

View File

@ -1,6 +1,6 @@
import net import net
fn test_dial() { fn test_dial() {
conn := net.dial('irc.freenode.org', 6667) //conn := net.dial('irc.freenode.org', 6667)
println(conn.sockfd) //println(conn.sockfd)
} }