]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - lhnet.c
DPrint the LHNET_Read and LHNET_Write errors (as they may just indicate lack of IPv6...
[xonotic/darkplaces.git] / lhnet.c
1
2 // Written by Forest Hale 2003-06-15 and placed into public domain.
3
4 #ifdef WIN32
5 #ifdef _MSC_VER
6 #pragma comment(lib, "ws2_32.lib")
7 #endif
8 # ifdef SUPPORTIPV6
9 // Windows XP or higher is required for getaddrinfo, but the inclusion of wspiapi provides fallbacks for older versions
10 # define _WIN32_WINNT 0x0501
11 # endif
12 # include <winsock2.h>
13 # include <ws2tcpip.h>
14 # ifdef USE_WSPIAPI_H
15 #  include <wspiapi.h>
16 # endif
17 #endif
18
19 #ifndef STANDALONETEST
20 #include "quakedef.h"
21 #endif
22
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <time.h>
26 #include <string.h>
27 #ifndef WIN32
28 #include <unistd.h>
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <sys/ioctl.h>
32 #include <errno.h>
33 #include <netdb.h>
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
36 #ifdef SUPPORTIPV6
37 #include <net/if.h>
38 #endif
39 #endif
40
41 #ifdef __MORPHOS__
42 #include <proto/socket.h>
43 #endif
44
45 // for Z_Malloc/Z_Free in quake
46 #ifndef STANDALONETEST
47 #include "zone.h"
48 #include "sys.h"
49 #include "netconn.h"
50 #else
51 #define Con_Print printf
52 #define Con_Printf printf
53 #define Z_Malloc malloc
54 #define Z_Free free
55 #endif
56
57 #include "lhnet.h"
58
59 #if defined(WIN32)
60 #define EWOULDBLOCK WSAEWOULDBLOCK
61 #define ECONNREFUSED WSAECONNREFUSED
62
63 #define SOCKETERRNO WSAGetLastError()
64
65 #define IOC_VENDOR 0x18000000
66 #define _WSAIOW(x,y) (IOC_IN|(x)|(y))
67 #define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
68
69 #define SOCKLEN_T int
70 #elif defined(__MORPHOS__)
71 #define ioctlsocket IoctlSocket
72 #define closesocket CloseSocket
73 #define SOCKETERRNO Errno()
74
75 #define SOCKLEN_T int
76 #else
77 #define ioctlsocket ioctl
78 #define closesocket close
79 #define SOCKETERRNO errno
80
81 #define SOCKLEN_T socklen_t
82 #endif
83
84 #ifdef MSG_DONTWAIT
85 #define LHNET_RECVFROM_FLAGS MSG_DONTWAIT
86 #define LHNET_SENDTO_FLAGS 0
87 #else
88 #define LHNET_RECVFROM_FLAGS 0
89 #define LHNET_SENDTO_FLAGS 0
90 #endif
91
92 typedef struct lhnetaddressnative_s
93 {
94         lhnetaddresstype_t addresstype;
95         int port;
96         union
97         {
98                 struct sockaddr sock;
99                 struct sockaddr_in in;
100 #ifdef SUPPORTIPV6
101                 struct sockaddr_in6 in6;
102 #endif
103         }
104         addr;
105 }
106 lhnetaddressnative_t;
107
108 // to make LHNETADDRESS_FromString resolve repeated hostnames faster, cache them
109 #define MAX_NAMECACHE 64
110 static struct namecache_s
111 {
112         lhnetaddressnative_t address;
113         double expirationtime;
114         char name[64];
115 }
116 namecache[MAX_NAMECACHE];
117 static int namecacheposition = 0;
118
119 int LHNETADDRESS_FromPort(lhnetaddress_t *vaddress, lhnetaddresstype_t addresstype, int port)
120 {
121         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
122         if (!address)
123                 return 0;
124         switch(addresstype)
125         {
126         default:
127                 break;
128         case LHNETADDRESSTYPE_LOOP:
129                 // local:port  (loopback)
130                 memset(address, 0, sizeof(*address));
131                 address->addresstype = LHNETADDRESSTYPE_LOOP;
132                 address->port = port;
133                 return 1;
134         case LHNETADDRESSTYPE_INET4:
135                 // 0.0.0.0:port  (INADDR_ANY, binds to all interfaces)
136                 memset(address, 0, sizeof(*address));
137                 address->addresstype = LHNETADDRESSTYPE_INET4;
138                 address->port = port;
139                 address->addr.in.sin_family = AF_INET;
140                 address->addr.in.sin_port = htons((unsigned short)port);
141                 return 1;
142 #ifdef SUPPORTIPV6
143         case LHNETADDRESSTYPE_INET6:
144                 // [0:0:0:0:0:0:0:0]:port  (IN6ADDR_ANY, binds to all interfaces)
145                 memset(address, 0, sizeof(*address));
146                 address->addresstype = LHNETADDRESSTYPE_INET6;
147                 address->port = port;
148                 address->addr.in6.sin6_family = AF_INET6;
149                 address->addr.in6.sin6_port = htons((unsigned short)port);
150                 return 1;
151 #endif
152         }
153         return 0;
154 }
155
156 #ifdef SUPPORTIPV6
157 int LHNETADDRESS_Resolve(lhnetaddressnative_t *address, const char *name, int port)
158 {
159         char port_buff [16];
160         struct addrinfo hints;
161         struct addrinfo* addrinf;
162         int err;
163
164         dpsnprintf (port_buff, sizeof (port_buff), "%d", port);
165         port_buff[sizeof (port_buff) - 1] = '\0';
166
167         memset(&hints, 0, sizeof (hints));
168         hints.ai_family = AF_UNSPEC;
169         hints.ai_socktype = SOCK_DGRAM;
170         //hints.ai_flags = AI_PASSIVE;
171
172         err = getaddrinfo(name, port_buff, &hints, &addrinf);
173         if (err != 0 || addrinf == NULL)
174                 return 0;
175         if (addrinf->ai_addr->sa_family != AF_INET6 && addrinf->ai_addr->sa_family != AF_INET)
176         {
177                 freeaddrinfo (addrinf);
178                 return 0;
179         }
180
181         // great it worked
182         if (addrinf->ai_addr->sa_family == AF_INET6)
183         {
184                 address->addresstype = LHNETADDRESSTYPE_INET6;
185                 memcpy(&address->addr.in6, addrinf->ai_addr, sizeof(address->addr.in6));
186         }
187         else
188         {
189                 address->addresstype = LHNETADDRESSTYPE_INET4;
190                 memcpy(&address->addr.in, addrinf->ai_addr, sizeof(address->addr.in));
191         }
192         address->port = port;
193         
194         freeaddrinfo (addrinf);
195         return 1;
196 }
197
198 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
199 {
200         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
201         int i, port, d1, d2, d3, d4, resolved;
202         size_t namelen;
203         unsigned char *a;
204         char name[128];
205 #ifdef STANDALONETEST
206         char string2[128];
207 #endif
208         const char* addr_start;
209         const char* addr_end = NULL;
210         const char* port_name = NULL;
211         int addr_family = AF_UNSPEC;
212
213         if (!address || !string || !*string)
214                 return 0;
215         memset(address, 0, sizeof(*address));
216         address->addresstype = LHNETADDRESSTYPE_NONE;
217         port = 0;
218
219         // If it's a bracketed IPv6 address
220         if (string[0] == '[')
221         {
222                 const char* end_bracket = strchr(string, ']');
223
224                 if (end_bracket == NULL)
225                         return 0;
226
227                 if (end_bracket[1] == ':')
228                         port_name = end_bracket + 2;
229                 else if (end_bracket[1] != '\0')
230                         return 0;
231
232                 addr_family = AF_INET6;
233                 addr_start = &string[1];
234                 addr_end = end_bracket;
235         }
236         else
237         {
238                 const char* first_colon;
239
240                 addr_start = string;
241
242                 // If it's a numeric non-bracket IPv6 address (-> no port),
243                 // or it's a numeric IPv4 address, or a name, with a port
244                 first_colon = strchr(string, ':');
245                 if (first_colon != NULL)
246                 {
247                         const char* last_colon = strrchr(first_colon + 1, ':');
248
249                         // If it's an numeric IPv4 address, or a name, with a port
250                         if (last_colon == NULL)
251                         {
252                                 addr_end = first_colon;
253                                 port_name = first_colon + 1;
254                         }
255                         else
256                                 addr_family = AF_INET6;
257                 }
258         }
259
260         if (addr_end != NULL)
261                 namelen = addr_end - addr_start;
262         else
263                 namelen = strlen (addr_start);
264
265         if (namelen >= sizeof(name))
266                 namelen = sizeof(name) - 1;
267         memcpy (name, addr_start, namelen);
268         name[namelen] = 0;
269
270         if (port_name)
271                 port = atoi(port_name);
272
273         if (port == 0)
274                 port = defaultport;
275
276         // handle loopback
277         if (!strcmp(name, "local"))
278         {
279                 address->addresstype = LHNETADDRESSTYPE_LOOP;
280                 address->port = port;
281                 return 1;
282         }
283         // try to parse as dotted decimal ipv4 address first
284         // note this supports partial ip addresses
285         d1 = d2 = d3 = d4 = 0;
286 #if _MSC_VER >= 1400
287 #define sscanf sscanf_s
288 #endif
289         if (addr_family != AF_INET6 &&
290                 sscanf(name, "%d.%d.%d.%d", &d1, &d2, &d3, &d4) >= 1 && (unsigned int)d1 < 256 && (unsigned int)d2 < 256 && (unsigned int)d3 < 256 && (unsigned int)d4 < 256)
291         {
292                 // parsed a valid ipv4 address
293                 address->addresstype = LHNETADDRESSTYPE_INET4;
294                 address->port = port;
295                 address->addr.in.sin_family = AF_INET;
296                 address->addr.in.sin_port = htons((unsigned short)port);
297                 a = (unsigned char *)&address->addr.in.sin_addr;
298                 a[0] = d1;
299                 a[1] = d2;
300                 a[2] = d3;
301                 a[3] = d4;
302 #ifdef STANDALONETEST
303                 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
304                 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %s\n", string, string2);
305 #endif
306                 return 1;
307         }
308         for (i = 0;i < MAX_NAMECACHE;i++)
309                 if (!strcmp(namecache[i].name, name))
310                         break;
311 #ifdef STANDALONETEST
312         if (i < MAX_NAMECACHE)
313 #else
314         if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
315 #endif
316         {
317                 *address = namecache[i].address;
318                 address->port = port;
319                 if (address->addresstype == LHNETADDRESSTYPE_INET6)
320                 {
321                         address->addr.in6.sin6_port = htons((unsigned short)port);
322                         return 1;
323                 }
324                 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
325                 {
326                         address->addr.in.sin_port = htons((unsigned short)port);
327                         return 1;
328                 }
329                 return 0;
330         }
331
332         for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
333                 namecache[namecacheposition].name[i] = name[i];
334         namecache[namecacheposition].name[i] = 0;
335 #ifndef STANDALONETEST
336         namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
337 #endif
338
339         // try resolving the address (handles dns and other ip formats)
340         resolved = LHNETADDRESS_Resolve(address, name, port);
341         if (resolved)
342         {
343 #ifdef STANDALONETEST
344                 const char *protoname;
345
346                 switch (address->addresstype)
347                 {
348                         case LHNETADDRESSTYPE_INET6:
349                                 protoname = "ipv6";
350                                 break;
351                         case LHNETADDRESSTYPE_INET4:
352                                 protoname = "ipv4";
353                                 break;
354                         default:
355                                 protoname = "UNKNOWN";
356                                 break;
357                 }
358                 LHNETADDRESS_ToString(vaddress, string2, sizeof(string2), 1);
359                 Con_Printf("LHNETADDRESS_Resolve(\"%s\") returned %s address %s\n", string, protoname, string2);
360 #endif
361                 namecache[namecacheposition].address = *address;
362         }
363         else
364         {
365 #ifdef STANDALONETEST
366                 printf("name resolution failed on address \"%s\"\n", name);
367 #endif
368                 namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
369         }
370         
371         namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
372         return resolved;
373 }
374 #else
375 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
376 {
377         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
378         int i, port, namelen, d1, d2, d3, d4;
379         struct hostent *hostentry;
380         unsigned char *a;
381         const char *colon;
382         char name[128];
383 #ifdef STANDALONETEST
384         char string2[128];
385 #endif
386         if (!address || !string || !*string)
387                 return 0;
388         memset(address, 0, sizeof(*address));
389         address->addresstype = LHNETADDRESSTYPE_NONE;
390         port = 0;
391         colon = strrchr(string, ':');
392         if (colon && (colon == strchr(string, ':') || (string[0] == '[' && colon - string > 0 && colon[-1] == ']')))
393         //           EITHER: colon is the ONLY colon  OR: colon comes after [...] delimited IPv6 address
394         //           fixes misparsing of IPv6 addresses without port
395         {
396                 port = atoi(colon + 1);
397         }
398         else
399                 colon = string + strlen(string);
400         if (port == 0)
401                 port = defaultport;
402         namelen = colon - string;
403         if (namelen > 127)
404                 namelen = 127;
405         if (string[0] == '[' && namelen > 0 && string[namelen-1] == ']') // ipv6
406         {
407                 string++;
408                 namelen -= 2;
409         }
410         memcpy(name, string, namelen);
411         name[namelen] = 0;
412         // handle loopback
413         if (!strcmp(name, "local"))
414         {
415                 address->addresstype = LHNETADDRESSTYPE_LOOP;
416                 address->port = port;
417                 return 1;
418         }
419         // try to parse as dotted decimal ipv4 address first
420         // note this supports partial ip addresses
421         d1 = d2 = d3 = d4 = 0;
422 #if _MSC_VER >= 1400
423 #define sscanf sscanf_s
424 #endif
425         if (sscanf(name, "%d.%d.%d.%d", &d1, &d2, &d3, &d4) >= 1 && (unsigned int)d1 < 256 && (unsigned int)d2 < 256 && (unsigned int)d3 < 256 && (unsigned int)d4 < 256)
426         {
427                 // parsed a valid ipv4 address
428                 address->addresstype = LHNETADDRESSTYPE_INET4;
429                 address->port = port;
430                 address->addr.in.sin_family = AF_INET;
431                 address->addr.in.sin_port = htons((unsigned short)port);
432                 a = (unsigned char *)&address->addr.in.sin_addr;
433                 a[0] = d1;
434                 a[1] = d2;
435                 a[2] = d3;
436                 a[3] = d4;
437 #ifdef STANDALONETEST
438                 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
439                 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %s\n", string, string2);
440 #endif
441                 return 1;
442         }
443         for (i = 0;i < MAX_NAMECACHE;i++)
444                 if (!strcmp(namecache[i].name, name))
445                         break;
446 #ifdef STANDALONETEST
447         if (i < MAX_NAMECACHE)
448 #else
449         if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
450 #endif
451         {
452                 *address = namecache[i].address;
453                 address->port = port;
454                 if (address->addresstype == LHNETADDRESSTYPE_INET6)
455                 {
456 #ifdef SUPPORTIPV6
457                         address->addr.in6.sin6_port = htons((unsigned short)port);
458                         return 1;
459 #endif
460                 }
461                 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
462                 {
463                         address->addr.in.sin_port = htons((unsigned short)port);
464                         return 1;
465                 }
466                 return 0;
467         }
468         // try gethostbyname (handles dns and other ip formats)
469         hostentry = gethostbyname(name);
470         if (hostentry)
471         {
472                 if (hostentry->h_addrtype == AF_INET6)
473                 {
474 #ifdef SUPPORTIPV6
475                         // great it worked
476                         address->addresstype = LHNETADDRESSTYPE_INET6;
477                         address->port = port;
478                         address->addr.in6.sin6_family = hostentry->h_addrtype;
479                         address->addr.in6.sin6_port = htons((unsigned short)port);
480                         memcpy(&address->addr.in6.sin6_addr, hostentry->h_addr_list[0], sizeof(address->addr.in6.sin6_addr));
481                         for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
482                                 namecache[namecacheposition].name[i] = name[i];
483                         namecache[namecacheposition].name[i] = 0;
484 #ifndef STANDALONETEST
485                         namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
486 #endif
487                         namecache[namecacheposition].address = *address;
488                         namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
489 #ifdef STANDALONETEST
490                         LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
491                         printf("gethostbyname(\"%s\") returned ipv6 address %s\n", string, string2);
492 #endif
493                         return 1;
494 #endif
495                 }
496                 else if (hostentry->h_addrtype == AF_INET)
497                 {
498                         // great it worked
499                         address->addresstype = LHNETADDRESSTYPE_INET4;
500                         address->port = port;
501                         address->addr.in.sin_family = hostentry->h_addrtype;
502                         address->addr.in.sin_port = htons((unsigned short)port);
503                         memcpy(&address->addr.in.sin_addr, hostentry->h_addr_list[0], sizeof(address->addr.in.sin_addr));
504                         for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
505                                 namecache[namecacheposition].name[i] = name[i];
506                         namecache[namecacheposition].name[i] = 0;
507 #ifndef STANDALONETEST
508                         namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
509 #endif
510                         namecache[namecacheposition].address = *address;
511                         namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
512 #ifdef STANDALONETEST
513                         LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
514                         printf("gethostbyname(\"%s\") returned ipv4 address %s\n", string, string2);
515 #endif
516                         return 1;
517                 }
518         }
519 #ifdef STANDALONETEST
520         printf("gethostbyname failed on address \"%s\"\n", name);
521 #endif
522         for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
523                 namecache[namecacheposition].name[i] = name[i];
524         namecache[namecacheposition].name[i] = 0;
525 #ifndef STANDALONETEST
526         namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
527 #endif
528         namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
529         namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
530         return 0;
531 }
532 #endif
533
534 int LHNETADDRESS_ToString(const lhnetaddress_t *vaddress, char *string, int stringbuffersize, int includeport)
535 {
536         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
537         const unsigned char *a;
538         *string = 0;
539         if (!address || !string || stringbuffersize < 1)
540                 return 0;
541         switch(address->addresstype)
542         {
543         default:
544                 break;
545         case LHNETADDRESSTYPE_LOOP:
546                 if (includeport)
547                 {
548                         if (stringbuffersize >= 12)
549                         {
550                                 dpsnprintf(string, stringbuffersize, "local:%d", address->port);
551                                 return 1;
552                         }
553                 }
554                 else
555                 {
556                         if (stringbuffersize >= 6)
557                         {
558                                 memcpy(string, "local", 6);
559                                 return 1;
560                         }
561                 }
562                 break;
563         case LHNETADDRESSTYPE_INET4:
564                 a = (const unsigned char *)(&address->addr.in.sin_addr);
565                 if (includeport)
566                 {
567                         if (stringbuffersize >= 22)
568                         {
569                                 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d:%d", a[0], a[1], a[2], a[3], address->port);
570                                 return 1;
571                         }
572                 }
573                 else
574                 {
575                         if (stringbuffersize >= 16)
576                         {
577                                 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
578                                 return 1;
579                         }
580                 }
581                 break;
582 #ifdef SUPPORTIPV6
583         case LHNETADDRESSTYPE_INET6:
584                 a = (const unsigned char *)(&address->addr.in6.sin6_addr);
585                 if (includeport)
586                 {
587                         if (stringbuffersize >= 88)
588                         {
589                                 dpsnprintf(string, stringbuffersize, "[%x:%x:%x:%x:%x:%x:%x:%x]:%d", a[0] * 256 + a[1], a[2] * 256 + a[3], a[4] * 256 + a[5], a[6] * 256 + a[7], a[8] * 256 + a[9], a[10] * 256 + a[11], a[12] * 256 + a[13], a[14] * 256 + a[15], address->port);
590                                 return 1;
591                         }
592                 }
593                 else
594                 {
595                         if (stringbuffersize >= 80)
596                         {
597                                 dpsnprintf(string, stringbuffersize, "%x:%x:%x:%x:%x:%x:%x:%x", a[0] * 256 + a[1], a[2] * 256 + a[3], a[4] * 256 + a[5], a[6] * 256 + a[7], a[8] * 256 + a[9], a[10] * 256 + a[11], a[12] * 256 + a[13], a[14] * 256 + a[15]);
598                                 return 1;
599                         }
600                 }
601                 break;
602 #endif
603         }
604         return 0;
605 }
606
607 int LHNETADDRESS_GetAddressType(const lhnetaddress_t *address)
608 {
609         if (address)
610                 return address->addresstype;
611         else
612                 return LHNETADDRESSTYPE_NONE;
613 }
614
615 const char *LHNETADDRESS_GetInterfaceName(const lhnetaddress_t *vaddress)
616 {
617 #ifdef SUPPORTIPV6
618         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
619
620         if (address && address->addresstype == LHNETADDRESSTYPE_INET6)
621         {
622 #ifndef _WIN32
623
624                 static char ifname [IF_NAMESIZE];
625                 
626                 if (if_indextoname(address->addr.in6.sin6_scope_id, ifname) == ifname)
627                         return ifname;
628
629 #else
630
631                 // The Win32 API doesn't have if_indextoname() until Windows Vista,
632                 // but luckily it just uses the interface ID as the interface name
633
634                 static char ifname [16];
635
636                 if (dpsnprintf(ifname, sizeof(ifname), "%lu", address->addr.in6.sin6_scope_id) > 0)
637                         return ifname;
638
639 #endif
640         }
641 #endif
642
643         return NULL;
644 }
645
646 int LHNETADDRESS_GetPort(const lhnetaddress_t *address)
647 {
648         if (!address)
649                 return -1;
650         return address->port;
651 }
652
653 int LHNETADDRESS_SetPort(lhnetaddress_t *vaddress, int port)
654 {
655         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
656         if (!address)
657                 return 0;
658         address->port = port;
659         switch(address->addresstype)
660         {
661         case LHNETADDRESSTYPE_LOOP:
662                 return 1;
663         case LHNETADDRESSTYPE_INET4:
664                 address->addr.in.sin_port = htons((unsigned short)port);
665                 return 1;
666 #ifdef SUPPORTIPV6
667         case LHNETADDRESSTYPE_INET6:
668                 address->addr.in6.sin6_port = htons((unsigned short)port);
669                 return 1;
670 #endif
671         default:
672                 return 0;
673         }
674 }
675
676 int LHNETADDRESS_Compare(const lhnetaddress_t *vaddress1, const lhnetaddress_t *vaddress2)
677 {
678         lhnetaddressnative_t *address1 = (lhnetaddressnative_t *)vaddress1;
679         lhnetaddressnative_t *address2 = (lhnetaddressnative_t *)vaddress2;
680         if (!address1 || !address2)
681                 return 1;
682         if (address1->addresstype != address2->addresstype)
683                 return 1;
684         switch(address1->addresstype)
685         {
686         case LHNETADDRESSTYPE_LOOP:
687                 if (address1->port != address2->port)
688                         return -1;
689                 return 0;
690         case LHNETADDRESSTYPE_INET4:
691                 if (address1->addr.in.sin_family != address2->addr.in.sin_family)
692                         return 1;
693                 if (memcmp(&address1->addr.in.sin_addr, &address2->addr.in.sin_addr, sizeof(address1->addr.in.sin_addr)))
694                         return 1;
695                 if (address1->port != address2->port)
696                         return -1;
697                 return 0;
698 #ifdef SUPPORTIPV6
699         case LHNETADDRESSTYPE_INET6:
700                 if (address1->addr.in6.sin6_family != address2->addr.in6.sin6_family)
701                         return 1;
702                 if (memcmp(&address1->addr.in6.sin6_addr, &address2->addr.in6.sin6_addr, sizeof(address1->addr.in6.sin6_addr)))
703                         return 1;
704                 if (address1->port != address2->port)
705                         return -1;
706                 return 0;
707 #endif
708         default:
709                 return 1;
710         }
711 }
712
713 typedef struct lhnetpacket_s
714 {
715         void *data;
716         int length;
717         int sourceport;
718         int destinationport;
719         time_t timeout;
720 #ifndef STANDALONETEST
721         double sentdoubletime;
722 #endif
723         struct lhnetpacket_s *next, *prev;
724 }
725 lhnetpacket_t;
726
727 static int lhnet_active;
728 static lhnetsocket_t lhnet_socketlist;
729 static lhnetpacket_t lhnet_packetlist;
730 #ifdef WIN32
731 static int lhnet_didWSAStartup = 0;
732 static WSADATA lhnet_winsockdata;
733 #endif
734
735 void LHNET_Init(void)
736 {
737         if (lhnet_active)
738                 return;
739         lhnet_socketlist.next = lhnet_socketlist.prev = &lhnet_socketlist;
740         lhnet_packetlist.next = lhnet_packetlist.prev = &lhnet_packetlist;
741         lhnet_active = 1;
742 #ifdef WIN32
743         lhnet_didWSAStartup = !WSAStartup(MAKEWORD(1, 1), &lhnet_winsockdata);
744         if (!lhnet_didWSAStartup)
745                 Con_Print("LHNET_Init: WSAStartup failed, networking disabled\n");
746 #endif
747 }
748
749 void LHNET_Shutdown(void)
750 {
751         lhnetpacket_t *p;
752         if (!lhnet_active)
753                 return;
754         while (lhnet_socketlist.next != &lhnet_socketlist)
755                 LHNET_CloseSocket(lhnet_socketlist.next);
756         while (lhnet_packetlist.next != &lhnet_packetlist)
757         {
758                 p = lhnet_packetlist.next;
759                 p->prev->next = p->next;
760                 p->next->prev = p->prev;
761                 Z_Free(p);
762         }
763 #ifdef WIN32
764         if (lhnet_didWSAStartup)
765         {
766                 lhnet_didWSAStartup = 0;
767                 WSACleanup();
768         }
769 #endif
770         lhnet_active = 0;
771 }
772
773 static const char *LHNETPRIVATE_StrError(void)
774 {
775 #ifdef WIN32
776         int i = WSAGetLastError();
777         switch (i)
778         {
779                 case WSAEINTR:           return "WSAEINTR";
780                 case WSAEBADF:           return "WSAEBADF";
781                 case WSAEACCES:          return "WSAEACCES";
782                 case WSAEFAULT:          return "WSAEFAULT";
783                 case WSAEINVAL:          return "WSAEINVAL";
784                 case WSAEMFILE:          return "WSAEMFILE";
785                 case WSAEWOULDBLOCK:     return "WSAEWOULDBLOCK";
786                 case WSAEINPROGRESS:     return "WSAEINPROGRESS";
787                 case WSAEALREADY:        return "WSAEALREADY";
788                 case WSAENOTSOCK:        return "WSAENOTSOCK";
789                 case WSAEDESTADDRREQ:    return "WSAEDESTADDRREQ";
790                 case WSAEMSGSIZE:        return "WSAEMSGSIZE";
791                 case WSAEPROTOTYPE:      return "WSAEPROTOTYPE";
792                 case WSAENOPROTOOPT:     return "WSAENOPROTOOPT";
793                 case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
794                 case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
795                 case WSAEOPNOTSUPP:      return "WSAEOPNOTSUPP";
796                 case WSAEPFNOSUPPORT:    return "WSAEPFNOSUPPORT";
797                 case WSAEAFNOSUPPORT:    return "WSAEAFNOSUPPORT";
798                 case WSAEADDRINUSE:      return "WSAEADDRINUSE";
799                 case WSAEADDRNOTAVAIL:   return "WSAEADDRNOTAVAIL";
800                 case WSAENETDOWN:        return "WSAENETDOWN";
801                 case WSAENETUNREACH:     return "WSAENETUNREACH";
802                 case WSAENETRESET:       return "WSAENETRESET";
803                 case WSAECONNABORTED:    return "WSAECONNABORTED";
804                 case WSAECONNRESET:      return "WSAECONNRESET";
805                 case WSAENOBUFS:         return "WSAENOBUFS";
806                 case WSAEISCONN:         return "WSAEISCONN";
807                 case WSAENOTCONN:        return "WSAENOTCONN";
808                 case WSAESHUTDOWN:       return "WSAESHUTDOWN";
809                 case WSAETOOMANYREFS:    return "WSAETOOMANYREFS";
810                 case WSAETIMEDOUT:       return "WSAETIMEDOUT";
811                 case WSAECONNREFUSED:    return "WSAECONNREFUSED";
812                 case WSAELOOP:           return "WSAELOOP";
813                 case WSAENAMETOOLONG:    return "WSAENAMETOOLONG";
814                 case WSAEHOSTDOWN:       return "WSAEHOSTDOWN";
815                 case WSAEHOSTUNREACH:    return "WSAEHOSTUNREACH";
816                 case WSAENOTEMPTY:       return "WSAENOTEMPTY";
817                 case WSAEPROCLIM:        return "WSAEPROCLIM";
818                 case WSAEUSERS:          return "WSAEUSERS";
819                 case WSAEDQUOT:          return "WSAEDQUOT";
820                 case WSAESTALE:          return "WSAESTALE";
821                 case WSAEREMOTE:         return "WSAEREMOTE";
822                 case WSAEDISCON:         return "WSAEDISCON";
823                 case 0:                  return "no error";
824                 default:                 return "unknown WSAE error";
825         }
826 #else
827         return strerror(errno);
828 #endif
829 }
830
831 void LHNET_SleepUntilPacket_Microseconds(int microseconds)
832 {
833 #ifdef FD_SET
834         fd_set fdreadset;
835         struct timeval tv;
836         int lastfd;
837         lhnetsocket_t *s;
838         FD_ZERO(&fdreadset);
839         lastfd = 0;
840         for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
841         {
842                 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
843                 {
844                         if (lastfd < s->inetsocket)
845                                 lastfd = s->inetsocket;
846 #if defined(WIN32) && !defined(_MSC_VER)
847                         FD_SET((int)s->inetsocket, &fdreadset);
848 #else
849                         FD_SET((unsigned int)s->inetsocket, &fdreadset);
850 #endif
851                 }
852         }
853         tv.tv_sec = microseconds / 1000000;
854         tv.tv_usec = microseconds % 1000000;
855         select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
856 #else
857         Sys_Sleep(microseconds);
858 #endif
859 }
860
861 lhnetsocket_t *LHNET_OpenSocket_Connectionless(lhnetaddress_t *address)
862 {
863         lhnetsocket_t *lhnetsocket, *s;
864         if (!address)
865                 return NULL;
866         lhnetsocket = (lhnetsocket_t *)Z_Malloc(sizeof(*lhnetsocket));
867         if (lhnetsocket)
868         {
869                 memset(lhnetsocket, 0, sizeof(*lhnetsocket));
870                 lhnetsocket->address = *address;
871                 switch(lhnetsocket->address.addresstype)
872                 {
873                 case LHNETADDRESSTYPE_LOOP:
874                         if (lhnetsocket->address.port == 0)
875                         {
876                                 // allocate a port dynamically
877                                 // this search will always terminate because there is never
878                                 // an allocated socket with port 0, so if the number wraps it
879                                 // will find the port is unused, and then refuse to use port
880                                 // 0, causing an intentional failure condition
881                                 lhnetsocket->address.port = 1024;
882                                 for (;;)
883                                 {
884                                         for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
885                                                 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
886                                                         break;
887                                         if (s == &lhnet_socketlist)
888                                                 break;
889                                         lhnetsocket->address.port++;
890                                 }
891                         }
892                         // check if the port is available
893                         for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
894                                 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
895                                         break;
896                         if (s == &lhnet_socketlist && lhnetsocket->address.port != 0)
897                         {
898                                 lhnetsocket->next = &lhnet_socketlist;
899                                 lhnetsocket->prev = lhnetsocket->next->prev;
900                                 lhnetsocket->next->prev = lhnetsocket;
901                                 lhnetsocket->prev->next = lhnetsocket;
902                                 return lhnetsocket;
903                         }
904                         break;
905                 case LHNETADDRESSTYPE_INET4:
906 #ifdef SUPPORTIPV6
907                 case LHNETADDRESSTYPE_INET6:
908 #endif
909 #ifdef WIN32
910                         if (lhnet_didWSAStartup)
911                         {
912 #endif
913 #ifdef SUPPORTIPV6
914                                 if ((lhnetsocket->inetsocket = socket(address->addresstype == LHNETADDRESSTYPE_INET6 ? PF_INET6 : PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1)
915 #else
916                                 if ((lhnetsocket->inetsocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1)
917 #endif
918                                 {
919 #ifdef WIN32
920                                         u_long _false = 0;
921 #endif
922 #ifdef MSG_DONTWAIT
923                                         if (1)
924 #else
925 #ifdef WIN32
926                                         u_long _true = 1;
927 #else
928                                         char _true = 1;
929 #endif
930                                         if (ioctlsocket(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
931 #endif
932                                         {
933 #ifdef IPV6_V6ONLY
934                                                 // We need to set this flag to tell the OS that we only listen on IPv6. If we don't
935                                                 // most OSes will create a dual-protocol socket that also listens on IPv4. In this case
936                                                 // if an IPv4 socket is already bound to the port we want, our bind() call will fail.
937                                                 int ipv6_only = 1;
938                                                 if (address->addresstype != LHNETADDRESSTYPE_INET6
939                                                         || setsockopt (lhnetsocket->inetsocket, IPPROTO_IPV6, IPV6_V6ONLY,
940                                                                                    (const char *)&ipv6_only, sizeof(ipv6_only)) == 0
941 #ifdef WIN32
942                                                         // The Win32 API only supports IPV6_V6ONLY since Windows Vista, but fortunately
943                                                         // the default value is what we want on Win32 anyway (IPV6_V6ONLY = true)
944                                                         || SOCKETERRNO == WSAENOPROTOOPT
945 #endif
946                                                         )
947 #endif
948                                                 {
949                                                         lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
950                                                         SOCKLEN_T namelen;
951                                                         int bindresult;
952 #ifdef SUPPORTIPV6
953                                                         if (address->addresstype == LHNETADDRESSTYPE_INET6)
954                                                         {
955                                                                 namelen = sizeof(localaddress->addr.in6);
956                                                                 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
957                                                                 if (bindresult != -1)
958                                                                         getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
959                                                         }
960                                                         else
961 #endif
962                                                         {
963                                                                 namelen = sizeof(localaddress->addr.in);
964                                                                 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
965                                                                 if (bindresult != -1)
966                                                                         getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
967                                                         }
968                                                         if (bindresult != -1)
969                                                         {
970                                                                 int i = 1;
971                                                                 // enable broadcast on this socket
972                                                                 setsockopt(lhnetsocket->inetsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i));
973                                                                 lhnetsocket->next = &lhnet_socketlist;
974                                                                 lhnetsocket->prev = lhnetsocket->next->prev;
975                                                                 lhnetsocket->next->prev = lhnetsocket;
976                                                                 lhnetsocket->prev->next = lhnetsocket;
977 #ifdef WIN32
978                                                                 if (ioctlsocket(lhnetsocket->inetsocket, SIO_UDP_CONNRESET, &_false) == -1)
979                                                                         Con_DPrintf("LHNET_OpenSocket_Connectionless: ioctlsocket SIO_UDP_CONNRESET returned error: %s\n", LHNETPRIVATE_StrError());
980 #endif
981                                                                 return lhnetsocket;
982                                                         }
983                                                         else
984                                                                 Con_Printf("LHNET_OpenSocket_Connectionless: bind returned error: %s\n", LHNETPRIVATE_StrError());
985                                                 }
986 #ifdef IPV6_V6ONLY
987                                                 else
988                                                         Con_Printf("LHNET_OpenSocket_Connectionless: setsockopt(IPV6_V6ONLY) returned error: %s\n", LHNETPRIVATE_StrError());
989 #endif
990                                         }
991                                         else
992                                                 Con_Printf("LHNET_OpenSocket_Connectionless: ioctlsocket returned error: %s\n", LHNETPRIVATE_StrError());
993                                         closesocket(lhnetsocket->inetsocket);
994                                 }
995                                 else
996                                         Con_Printf("LHNET_OpenSocket_Connectionless: socket returned error: %s\n", LHNETPRIVATE_StrError());
997 #ifdef WIN32
998                         }
999                         else
1000                                 Con_Print("LHNET_OpenSocket_Connectionless: can't open a socket (WSAStartup failed during LHNET_Init)\n");
1001 #endif
1002                         break;
1003                 default:
1004                         break;
1005                 }
1006                 Z_Free(lhnetsocket);
1007         }
1008         return NULL;
1009 }
1010
1011 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
1012 {
1013         if (lhnetsocket)
1014         {
1015                 // unlink from socket list
1016                 if (lhnetsocket->next == NULL)
1017                         return; // invalid!
1018                 lhnetsocket->next->prev = lhnetsocket->prev;
1019                 lhnetsocket->prev->next = lhnetsocket->next;
1020                 lhnetsocket->next = NULL;
1021                 lhnetsocket->prev = NULL;
1022
1023                 // no special close code for loopback, just inet
1024                 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1025                 {
1026                         closesocket(lhnetsocket->inetsocket);
1027                 }
1028                 Z_Free(lhnetsocket);
1029         }
1030 }
1031
1032 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
1033 {
1034         if (sock)
1035                 return &sock->address;
1036         else
1037                 return NULL;
1038 }
1039
1040 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *vaddress)
1041 {
1042         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
1043         int value = 0;
1044         if (!lhnetsocket || !address || !content || maxcontentlength < 1)
1045                 return -1;
1046         if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
1047         {
1048                 time_t currenttime;
1049                 lhnetpacket_t *p, *pnext;
1050                 // scan for any old packets to timeout while searching for a packet
1051                 // that is waiting to be delivered to this socket
1052                 currenttime = time(NULL);
1053                 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
1054                 {
1055                         pnext = p->next;
1056                         if (p->timeout < currenttime)
1057                         {
1058                                 // unlink and free
1059                                 p->next->prev = p->prev;
1060                                 p->prev->next = p->next;
1061                                 Z_Free(p);
1062                                 continue;
1063                         }
1064 #ifndef STANDALONETEST
1065                         if (cl_netlocalping.value && (realtime - cl_netlocalping.value * (1.0 / 2000.0)) < p->sentdoubletime)
1066                                 continue;
1067 #endif
1068                         if (value == 0 && p->destinationport == lhnetsocket->address.port)
1069                         {
1070                                 if (p->length <= maxcontentlength)
1071                                 {
1072                                         lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
1073                                         *address = *localaddress;
1074                                         address->port = p->sourceport;
1075                                         memcpy(content, p->data, p->length);
1076                                         value = p->length;
1077                                 }
1078                                 else
1079                                         value = -1;
1080                                 // unlink and free
1081                                 p->next->prev = p->prev;
1082                                 p->prev->next = p->next;
1083                                 Z_Free(p);
1084                         }
1085                 }
1086         }
1087         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
1088         {
1089                 SOCKLEN_T inetaddresslength;
1090                 address->addresstype = LHNETADDRESSTYPE_NONE;
1091                 inetaddresslength = sizeof(address->addr.in);
1092                 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, LHNET_RECVFROM_FLAGS, &address->addr.sock, &inetaddresslength);
1093                 if (value > 0)
1094                 {
1095                         address->addresstype = LHNETADDRESSTYPE_INET4;
1096                         address->port = ntohs(address->addr.in.sin_port);
1097                         return value;
1098                 }
1099                 else if (value < 0)
1100                 {
1101                         int e = SOCKETERRNO;
1102                         if (e == EWOULDBLOCK)
1103                                 return 0;
1104                         switch (e)
1105                         {
1106                                 case ECONNREFUSED:
1107                                         Con_Print("Connection refused\n");
1108                                         return 0;
1109                         }
1110                         Con_DPrintf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
1111                 }
1112         }
1113 #ifdef SUPPORTIPV6
1114         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1115         {
1116                 SOCKLEN_T inetaddresslength;
1117                 address->addresstype = LHNETADDRESSTYPE_NONE;
1118                 inetaddresslength = sizeof(address->addr.in6);
1119                 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, LHNET_RECVFROM_FLAGS, &address->addr.sock, &inetaddresslength);
1120                 if (value > 0)
1121                 {
1122                         address->addresstype = LHNETADDRESSTYPE_INET6;
1123                         address->port = ntohs(address->addr.in6.sin6_port);
1124                         return value;
1125                 }
1126                 else if (value == -1)
1127                 {
1128                         int e = SOCKETERRNO;
1129                         if (e == EWOULDBLOCK)
1130                                 return 0;
1131                         switch (e)
1132                         {
1133                                 case ECONNREFUSED:
1134                                         Con_Print("Connection refused\n");
1135                                         return 0;
1136                         }
1137                         Con_DPrintf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
1138                 }
1139         }
1140 #endif
1141         return value;
1142 }
1143
1144 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *vaddress)
1145 {
1146         lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
1147         int value = -1;
1148         if (!lhnetsocket || !address || !content || contentlength < 1)
1149                 return -1;
1150         if (lhnetsocket->address.addresstype != address->addresstype)
1151                 return -1;
1152         if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
1153         {
1154                 lhnetpacket_t *p;
1155                 p = (lhnetpacket_t *)Z_Malloc(sizeof(*p) + contentlength);
1156                 p->data = (void *)(p + 1);
1157                 memcpy(p->data, content, contentlength);
1158                 p->length = contentlength;
1159                 p->sourceport = lhnetsocket->address.port;
1160                 p->destinationport = address->port;
1161                 p->timeout = time(NULL) + 10;
1162                 p->next = &lhnet_packetlist;
1163                 p->prev = p->next->prev;
1164                 p->next->prev = p;
1165                 p->prev->next = p;
1166 #ifndef STANDALONETEST
1167                 p->sentdoubletime = realtime;
1168 #endif
1169                 value = contentlength;
1170         }
1171         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
1172         {
1173                 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, LHNET_SENDTO_FLAGS, (struct sockaddr *)&address->addr.in, sizeof(struct sockaddr_in));
1174                 if (value == -1)
1175                 {
1176                         if (SOCKETERRNO == EWOULDBLOCK)
1177                                 return 0;
1178                         Con_DPrintf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
1179                 }
1180         }
1181 #ifdef SUPPORTIPV6
1182         else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1183         {
1184                 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, 0, (struct sockaddr *)&address->addr.in6, sizeof(struct sockaddr_in6));
1185                 if (value == -1)
1186                 {
1187                         if (SOCKETERRNO == EWOULDBLOCK)
1188                                 return 0;
1189                         Con_DPrintf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
1190                 }
1191         }
1192 #endif
1193         return value;
1194 }
1195
1196 #ifdef STANDALONETEST
1197 int main(int argc, char **argv)
1198 {
1199 #if 1
1200         char *buffer = "test", buffer2[1024];
1201         int blen = strlen(buffer);
1202         int b2len = 1024;
1203         lhnetsocket_t *sock1;
1204         lhnetsocket_t *sock2;
1205         lhnetaddress_t myaddy1;
1206         lhnetaddress_t myaddy2;
1207         lhnetaddress_t myaddy3;
1208         lhnetaddress_t localhostaddy1;
1209         lhnetaddress_t localhostaddy2;
1210         int test1;
1211         int test2;
1212
1213         printf("calling LHNET_Init\n");
1214         LHNET_Init();
1215
1216         printf("calling LHNET_FromPort twice to create two local addresses\n");
1217         LHNETADDRESS_FromPort(&myaddy1, LHNETADDRESSTYPE_INET4, 4000);
1218         LHNETADDRESS_FromPort(&myaddy2, LHNETADDRESSTYPE_INET4, 4001);
1219         LHNETADDRESS_FromString(&localhostaddy1, "127.0.0.1", 4000);
1220         LHNETADDRESS_FromString(&localhostaddy2, "127.0.0.1", 4001);
1221
1222         printf("calling LHNET_OpenSocket_Connectionless twice to create two local sockets\n");
1223         sock1 = LHNET_OpenSocket_Connectionless(&myaddy1);
1224         sock2 = LHNET_OpenSocket_Connectionless(&myaddy2);
1225
1226         printf("calling LHNET_Write to send a packet from the first socket to the second socket\n");
1227         test1 = LHNET_Write(sock1, buffer, blen, &localhostaddy2);
1228         printf("sleeping briefly\n");
1229 #ifdef WIN32
1230         Sleep (100);
1231 #else
1232         usleep (100000);
1233 #endif
1234         printf("calling LHNET_Read on the second socket to read the packet sent from the first socket\n");
1235         test2 = LHNET_Read(sock2, buffer2, b2len - 1, &myaddy3);
1236         if (test2 > 0)
1237                 Con_Printf("socket to socket test succeeded\n");
1238         else
1239                 Con_Printf("socket to socket test failed\n");
1240
1241 #ifdef WIN32
1242         printf("press any key to exit\n");
1243         getchar();
1244 #endif
1245
1246         printf("calling LHNET_Shutdown\n");
1247         LHNET_Shutdown();
1248         printf("exiting\n");
1249         return 0;
1250 #else
1251         lhnetsocket_t *sock[16], *sendsock;
1252         int i;
1253         int numsockets;
1254         int count;
1255         int length;
1256         int port;
1257         time_t oldtime;
1258         time_t newtime;
1259         char *sendmessage;
1260         int sendmessagelength;
1261         lhnetaddress_t destaddress;
1262         lhnetaddress_t receiveaddress;
1263         lhnetaddress_t sockaddress[16];
1264         char buffer[1536], addressstring[128], addressstring2[128];
1265         if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
1266         {
1267                 printf("calling LHNET_Init()\n");
1268                 LHNET_Init();
1269
1270                 numsockets = 0;
1271                 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
1272                 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
1273                 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
1274
1275                 sendsock = NULL;
1276                 sendmessage = NULL;
1277                 sendmessagelength = 0;
1278
1279                 for (i = 0;i < numsockets;i++)
1280                 {
1281                         LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
1282                         printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
1283                         if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
1284                         {
1285                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1286                                 printf("opened socket successfully (address \"%s\")\n", addressstring2);
1287                         }
1288                         else
1289                         {
1290                                 printf("failed to open socket\n");
1291                                 if (i == 0)
1292                                 {
1293                                         LHNET_Shutdown();
1294                                         return -1;
1295                                 }
1296                         }
1297                 }
1298                 count = 0;
1299                 if (argc == 5)
1300                 {
1301                         count = atoi(argv[2]);
1302                         if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
1303                         {
1304                                 sendmessage = argv[4];
1305                                 sendmessagelength = strlen(sendmessage);
1306                                 sendsock = NULL;
1307                                 for (i = 0;i < numsockets;i++)
1308                                         if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
1309                                                 sendsock = sock[i];
1310                                 if (sendsock == NULL)
1311                                 {
1312                                         printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
1313                                         argc = 2;
1314                                 }
1315                         }
1316                         else
1317                         {
1318                                 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
1319                                 argc = 2;
1320                         }
1321                 }
1322                 printf("started, now listening for \"exit\" on the opened sockets\n");
1323                 oldtime = time(NULL);
1324                 for(;;)
1325                 {
1326 #ifdef WIN32
1327                         Sleep(1);
1328 #else
1329                         usleep(1);
1330 #endif
1331                         for (i = 0;i < numsockets;i++)
1332                         {
1333                                 if (sock[i])
1334                                 {
1335                                         length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
1336                                         if (length < 0)
1337                                                 printf("localsock read error: length < 0");
1338                                         else if (length > 0 && length < (int)sizeof(buffer))
1339                                         {
1340                                                 buffer[length] = 0;
1341                                                 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
1342                                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1343                                                 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
1344                                                 if (!strcmp(buffer, "exit"))
1345                                                         break;
1346                                         }
1347                                 }
1348                         }
1349                         if (i < numsockets)
1350                                 break;
1351                         if (argc == 5 && count > 0)
1352                         {
1353                                 newtime = time(NULL);
1354                                 if (newtime != oldtime)
1355                                 {
1356                                         LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
1357                                         LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
1358                                         printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
1359                                         length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
1360                                         if (length == sendmessagelength)
1361                                                 printf("sent successfully\n");
1362                                         else
1363                                                 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
1364                                         oldtime = newtime;
1365                                         count--;
1366                                         if (count <= 0)
1367                                                 printf("Done sending, still listening for \"exit\"\n");
1368                                 }
1369                         }
1370                 }
1371                 for (i = 0;i < numsockets;i++)
1372                 {
1373                         if (sock[i])
1374                         {
1375                                 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1376                                 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
1377                                 LHNET_CloseSocket(sock[i]);
1378                         }
1379                 }
1380                 printf("calling LHNET_Shutdown()\n");
1381                 LHNET_Shutdown();
1382                 return 0;
1383         }
1384         printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");
1385         return -1;
1386 #endif
1387 }
1388 #endif
1389