Last active
April 23, 2019 04:32
-
-
Save jrfondren/686c11eeea416be0767ac72ac7a6b3eb to your computer and use it in GitHub Desktop.
the simplest and highest-level possible initialization of a server socket in Nim
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{.emit: """ | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netdb.h> | |
""".} | |
type | |
ServerSocket = distinct int | |
ClientSocket = distinct int | |
Port = distinct int16 | |
AddrInfo {.header: "<netdb.h>", importc: "struct addrinfo".} = object | |
AddrInfoPtr = ptr AddrInfo | |
proc initServerSocket(port: Port): ServerSocket = | |
var | |
hints: AddrInfo | |
res: AddrInfoPtr | |
yes = 1 | |
strPort = $ int(port) | |
{.emit: [hints, ".ai_family = AF_UNSPEC;"].} | |
{.emit: [hints, ".ai_socktype = SOCK_STREAM;"].} | |
{.emit: [hints, ".ai_flags = AI_PASSIVE;"].} | |
{.emit: [ "getaddrinfo(NULL, ", cstring(strPort), ", ", addr(hints), ", ", addr(res), ");" ].} | |
defer: | |
{.emit: [ "freeaddrinfo(", res, ");" ].} | |
{.emit: [ result, " = socket(", res, "->ai_family, ", res, "->ai_socktype, ", res, "->ai_protocol);" ].} | |
if -1 == int(result): raise newException(IOError, "socket() failure") | |
var iores: int | |
{.emit: [ iores, " = setsockopt(", result, ", SOL_SOCKET, SO_REUSEADDR, ", addr(yes), ", ", sizeof(yes), ");" ].} | |
if -1 == iores: raise newException(IOError, "setsockopt() failure") | |
{.emit: [ iores, " = bind(", result, ", ", res, "->ai_addr, ", res, "->ai_addrlen);" ].} | |
if -1 == iores: raise newException(IOError, "bind() failure") | |
{.emit: [ iores, " = listen(", result, ", 4);" ].} | |
let serv = initServerSocket(Port(4001)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment