1 /**
2  * @file net/sock.c  Networking sockets code
3  *
4  * Copyright (C) 2010 Creytiv.com
5  */
6 #include <re_types.h>
7 #include <re_fmt.h>
8 #include <re_mbuf.h>
9 #include <re_net.h>
10 
11 
12 #define DEBUG_MODULE "netsock"
13 #define DEBUG_LEVEL 5
14 #include <re_dbg.h>
15 
16 
17 static bool inited = false;
18 
19 
20 #ifdef WIN32
wsa_init(void)21 static int wsa_init(void)
22 {
23 	WORD wVersionRequested = MAKEWORD(2, 2);
24 	WSADATA wsaData;
25 	int err;
26 
27 	err = WSAStartup(wVersionRequested, &wsaData);
28 	if (err != 0) {
29 		DEBUG_WARNING("Could not load winsock (%m)\n", err);
30 		return err;
31 	}
32 
33 	/* Confirm that the WinSock DLL supports 2.2.*/
34 	/* Note that if the DLL supports versions greater    */
35 	/* than 2.2 in addition to 2.2, it will still return */
36 	/* 2.2 in wVersion since that is the version we      */
37 	/* requested.                                        */
38 	if (LOBYTE(wsaData.wVersion) != 2 ||
39 	    HIBYTE(wsaData.wVersion) != 2 ) {
40 		WSACleanup();
41 		DEBUG_WARNING("Bad winsock verion (%d.%d)\n",
42 			      HIBYTE(wsaData.wVersion),
43 			      LOBYTE(wsaData.wVersion));
44 		return EINVAL;
45 	}
46 
47 	return 0;
48 }
49 #endif
50 
51 
52 /**
53  * Initialise network sockets
54  *
55  * @return 0 if success, otherwise errorcode
56  */
net_sock_init(void)57 int net_sock_init(void)
58 {
59 	int err = 0;
60 
61 	DEBUG_INFO("sock init: inited=%d\n", inited);
62 
63 	if (inited)
64 		return 0;
65 
66 #ifdef WIN32
67 	err = wsa_init();
68 #endif
69 
70 	inited = true;
71 
72 	return err;
73 }
74 
75 
76 /**
77  * Cleanup network sockets
78  */
net_sock_close(void)79 void net_sock_close(void)
80 {
81 #ifdef WIN32
82 	const int err = WSACleanup();
83 	if (0 != err) {
84 		DEBUG_WARNING("sock close: WSACleanup (%d)\n", err);
85 	}
86 #endif
87 
88 	inited = false;
89 
90 	DEBUG_INFO("sock close\n");
91 }
92