summaryrefslogtreecommitdiff
path: root/xs_socket.h
diff options
context:
space:
mode:
authorGravatar default2022-09-19 20:41:11 +0200
committerGravatar default2022-09-19 20:41:11 +0200
commit67288a763b8bceadbb128d2cf5bdc431ba8a686f (patch)
tree0a0bc1922016bbd3d3cd2ec3c80a033970280a9f /xs_socket.h
parentProject started. (diff)
downloadsnac2-67288a763b8bceadbb128d2cf5bdc431ba8a686f.tar.gz
snac2-67288a763b8bceadbb128d2cf5bdc431ba8a686f.tar.xz
snac2-67288a763b8bceadbb128d2cf5bdc431ba8a686f.zip
Imported xs.
Diffstat (limited to 'xs_socket.h')
-rw-r--r--xs_socket.h95
1 files changed, 95 insertions, 0 deletions
diff --git a/xs_socket.h b/xs_socket.h
new file mode 100644
index 0000000..c5eab80
--- /dev/null
+++ b/xs_socket.h
@@ -0,0 +1,95 @@
1/* copyright (c) 2022 grunfink - MIT license */
2
3#ifndef _XS_SOCKET_H
4
5#define _XS_SOCKET_H
6
7int xs_socket_timeout(int s, float rto, float sto);
8int xs_socket_server(char *addr, int port);
9FILE *xs_socket_accept(int rs);
10
11
12#ifdef XS_IMPLEMENTATION
13
14#include <sys/socket.h>
15#include <netdb.h>
16#include <netinet/in.h>
17
18
19int xs_socket_timeout(int s, float rto, float sto)
20/* sets the socket timeout in seconds */
21{
22 struct timeval tv;
23 int ret = 0;
24
25 if (rto > 0.0) {
26 tv.tv_sec = (int)rto;
27 tv.tv_usec = (int)((rto - (float)(int)rto) * 1000000.0);
28
29 ret = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
30 }
31
32 if (sto > 0.0) {
33 tv.tv_sec = (int)sto;
34 tv.tv_usec = (int)((sto - (float)(int)sto) * 1000000.0);
35
36 ret = setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));
37 }
38
39 return ret;
40}
41
42
43int xs_socket_server(char *addr, int port)
44/* opens a server socket */
45{
46 int rs = -1;
47 struct sockaddr_in host;
48
49 memset(&host, '\0', sizeof(host));
50
51 if (addr != NULL) {
52 struct hostent *he;
53
54 if ((he = gethostbyname(addr)) != NULL)
55 memcpy(&host.sin_addr, he->h_addr_list[0], he->h_length);
56 else
57 goto end;
58 }
59
60 host.sin_family = AF_INET;
61 host.sin_port = htons(port);
62
63 if ((rs = socket(AF_INET, SOCK_STREAM, 0)) != -1) {
64 /* reuse addr */
65 int i = 1;
66 setsockopt(rs, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i));
67
68 if (bind(rs, (struct sockaddr *)&host, sizeof(host)) == -1) {
69 close(rs);
70 rs = -1;
71 }
72 else
73 listen(rs, SOMAXCONN);
74 }
75
76end:
77 return rs;
78}
79
80
81FILE *xs_socket_accept(int rs)
82/* accepts an incoming connection */
83{
84 int cs = -1;
85 struct sockaddr_in host;
86 socklen_t l = sizeof(host);
87
88 cs = accept(rs, (struct sockaddr *)&host, &l);
89
90 return cs == -1 ? NULL : fdopen(cs, "r+");
91}
92
93#endif /* XS_IMPLEMENTATION */
94
95#endif /* _XS_SOCKET_H */ \ No newline at end of file