by yakubin · 5y ago · 0 comments
Well, some APIs are not meant to be used directly, but hidden behind a class or more application-specific functions.
I've made my own wrapper a few times but often don't get to use it for various reasons.
int tcp_connect(char* remote_host, short int port, options* options, static char** error_string);
int tcp_listen(short int port, options* options, static char** error_string);
int udp_listen(short int port, options* options, static char** error_string);
Does any necessary lookups for you and connects sets up the socket. The options structure can be NULL if you want the sane defaults, or you can zero it out and set only the options you care about like the connect timeout or flags like SO_REUSEADDR or O_NONBLOCK. Returns the socket number or -1 if an error occurs. In the event of an error the error_string is also set. The _listen variants spit out a socket ready for an accept() call.If you need something weird then you're back to the low level BSD socket stuff, but this covers about 95% of my use cases. While it's only saving a handful of system calls, it ends up being quite a bit of boilerplate and error handling. Especially if you specify a connect timeout, since that is kind of awkward to do with the BSD socket API.