2 // Written by Forest Hale 2003-06-15 and placed into public domain.
6 #pragma comment(lib, "ws2_32.lib")
9 // Windows XP or higher is required for getaddrinfo, but the inclusion of wspiapi provides fallbacks for older versions
10 # define _WIN32_WINNT 0x0501
12 # include <winsock2.h>
13 # include <ws2tcpip.h>
19 #ifndef STANDALONETEST
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <sys/ioctl.h>
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
42 #include <proto/socket.h>
45 // for Z_Malloc/Z_Free in quake
46 #ifndef STANDALONETEST
51 #define Con_Print printf
52 #define Con_Printf printf
53 #define Z_Malloc malloc
60 #define EWOULDBLOCK WSAEWOULDBLOCK
61 #define ECONNREFUSED WSAECONNREFUSED
63 #define SOCKETERRNO WSAGetLastError()
65 #define IOC_VENDOR 0x18000000
66 #define _WSAIOW(x,y) (IOC_IN|(x)|(y))
67 #define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
70 #elif defined(__MORPHOS__)
71 #define ioctlsocket IoctlSocket
72 #define closesocket CloseSocket
73 #define SOCKETERRNO Errno()
77 #define ioctlsocket ioctl
78 #define closesocket close
79 #define SOCKETERRNO errno
81 #define SOCKLEN_T socklen_t
85 #define LHNET_RECVFROM_FLAGS MSG_DONTWAIT
86 #define LHNET_SENDTO_FLAGS 0
88 #define LHNET_RECVFROM_FLAGS 0
89 #define LHNET_SENDTO_FLAGS 0
92 typedef struct lhnetaddressnative_s
94 lhnetaddresstype_t addresstype;
99 struct sockaddr_in in;
101 struct sockaddr_in6 in6;
106 lhnetaddressnative_t;
108 // to make LHNETADDRESS_FromString resolve repeated hostnames faster, cache them
109 #define MAX_NAMECACHE 64
110 static struct namecache_s
112 lhnetaddressnative_t address;
113 double expirationtime;
116 namecache[MAX_NAMECACHE];
117 static int namecacheposition = 0;
119 int LHNETADDRESS_FromPort(lhnetaddress_t *vaddress, lhnetaddresstype_t addresstype, int port)
121 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
128 case LHNETADDRESSTYPE_LOOP:
129 // local:port (loopback)
130 memset(address, 0, sizeof(*address));
131 address->addresstype = LHNETADDRESSTYPE_LOOP;
132 address->port = port;
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);
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);
157 static int LHNETADDRESS_Resolve(lhnetaddressnative_t *address, const char *name, int port)
160 struct addrinfo hints;
161 struct addrinfo* addrinf;
164 dpsnprintf (port_buff, sizeof (port_buff), "%d", port);
165 port_buff[sizeof (port_buff) - 1] = '\0';
167 memset(&hints, 0, sizeof (hints));
168 hints.ai_family = AF_UNSPEC;
169 hints.ai_socktype = SOCK_DGRAM;
170 //hints.ai_flags = AI_PASSIVE;
172 err = getaddrinfo(name, port_buff, &hints, &addrinf);
173 if (err != 0 || addrinf == NULL)
175 if (addrinf->ai_addr->sa_family != AF_INET6 && addrinf->ai_addr->sa_family != AF_INET)
177 freeaddrinfo (addrinf);
182 if (addrinf->ai_addr->sa_family == AF_INET6)
184 address->addresstype = LHNETADDRESSTYPE_INET6;
185 memcpy(&address->addr.in6, addrinf->ai_addr, sizeof(address->addr.in6));
189 address->addresstype = LHNETADDRESSTYPE_INET4;
190 memcpy(&address->addr.in, addrinf->ai_addr, sizeof(address->addr.in));
192 address->port = port;
194 freeaddrinfo (addrinf);
198 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
200 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
201 int i, port, d1, d2, d3, d4, resolved;
205 #ifdef STANDALONETEST
208 const char* addr_start;
209 const char* addr_end = NULL;
210 const char* port_name = NULL;
211 int addr_family = AF_UNSPEC;
213 if (!address || !string || !*string)
215 memset(address, 0, sizeof(*address));
216 address->addresstype = LHNETADDRESSTYPE_NONE;
219 // If it's a bracketed IPv6 address
220 if (string[0] == '[')
222 const char* end_bracket = strchr(string, ']');
224 if (end_bracket == NULL)
227 if (end_bracket[1] == ':')
228 port_name = end_bracket + 2;
229 else if (end_bracket[1] != '\0')
232 addr_family = AF_INET6;
233 addr_start = &string[1];
234 addr_end = end_bracket;
238 const char* first_colon;
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)
247 const char* last_colon = strrchr(first_colon + 1, ':');
249 // If it's an numeric IPv4 address, or a name, with a port
250 if (last_colon == NULL)
252 addr_end = first_colon;
253 port_name = first_colon + 1;
256 addr_family = AF_INET6;
260 if (addr_end != NULL)
261 namelen = addr_end - addr_start;
263 namelen = strlen (addr_start);
265 if (namelen >= sizeof(name))
266 namelen = sizeof(name) - 1;
267 memcpy (name, addr_start, namelen);
271 port = atoi(port_name);
277 if (!strcmp(name, "local"))
279 address->addresstype = LHNETADDRESSTYPE_LOOP;
280 address->port = port;
283 // try to parse as dotted decimal ipv4 address first
284 // note this supports partial ip addresses
285 d1 = d2 = d3 = d4 = 0;
287 #define sscanf sscanf_s
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)
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;
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);
308 for (i = 0;i < MAX_NAMECACHE;i++)
309 if (!strcmp(namecache[i].name, name))
311 #ifdef STANDALONETEST
312 if (i < MAX_NAMECACHE)
314 if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
317 *address = namecache[i].address;
318 address->port = port;
319 if (address->addresstype == LHNETADDRESSTYPE_INET6)
321 address->addr.in6.sin6_port = htons((unsigned short)port);
324 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
326 address->addr.in.sin_port = htons((unsigned short)port);
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
339 // try resolving the address (handles dns and other ip formats)
340 resolved = LHNETADDRESS_Resolve(address, name, port);
343 #ifdef STANDALONETEST
344 const char *protoname;
346 switch (address->addresstype)
348 case LHNETADDRESSTYPE_INET6:
351 case LHNETADDRESSTYPE_INET4:
355 protoname = "UNKNOWN";
358 LHNETADDRESS_ToString(vaddress, string2, sizeof(string2), 1);
359 Con_Printf("LHNETADDRESS_Resolve(\"%s\") returned %s address %s\n", string, protoname, string2);
361 namecache[namecacheposition].address = *address;
365 #ifdef STANDALONETEST
366 printf("name resolution failed on address \"%s\"\n", name);
368 namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
371 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
375 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
377 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
378 int i, port, namelen, d1, d2, d3, d4;
379 struct hostent *hostentry;
383 #ifdef STANDALONETEST
386 if (!address || !string || !*string)
388 memset(address, 0, sizeof(*address));
389 address->addresstype = LHNETADDRESSTYPE_NONE;
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
396 port = atoi(colon + 1);
399 colon = string + strlen(string);
402 namelen = colon - string;
405 if (string[0] == '[' && namelen > 0 && string[namelen-1] == ']') // ipv6
410 memcpy(name, string, namelen);
413 if (!strcmp(name, "local"))
415 address->addresstype = LHNETADDRESSTYPE_LOOP;
416 address->port = port;
419 // try to parse as dotted decimal ipv4 address first
420 // note this supports partial ip addresses
421 d1 = d2 = d3 = d4 = 0;
423 #define sscanf sscanf_s
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)
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;
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);
443 for (i = 0;i < MAX_NAMECACHE;i++)
444 if (!strcmp(namecache[i].name, name))
446 #ifdef STANDALONETEST
447 if (i < MAX_NAMECACHE)
449 if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
452 *address = namecache[i].address;
453 address->port = port;
454 if (address->addresstype == LHNETADDRESSTYPE_INET6)
457 address->addr.in6.sin6_port = htons((unsigned short)port);
461 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
463 address->addr.in.sin_port = htons((unsigned short)port);
468 // try gethostbyname (handles dns and other ip formats)
469 hostentry = gethostbyname(name);
472 if (hostentry->h_addrtype == AF_INET6)
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
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);
496 else if (hostentry->h_addrtype == AF_INET)
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
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);
519 #ifdef STANDALONETEST
520 printf("gethostbyname failed on address \"%s\"\n", name);
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
528 namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
529 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
534 int LHNETADDRESS_ToString(const lhnetaddress_t *vaddress, char *string, int stringbuffersize, int includeport)
536 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
537 const unsigned char *a;
539 if (!address || !string || stringbuffersize < 1)
541 switch(address->addresstype)
545 case LHNETADDRESSTYPE_LOOP:
548 if (stringbuffersize >= 12)
550 dpsnprintf(string, stringbuffersize, "local:%d", address->port);
556 if (stringbuffersize >= 6)
558 memcpy(string, "local", 6);
563 case LHNETADDRESSTYPE_INET4:
564 a = (const unsigned char *)(&address->addr.in.sin_addr);
567 if (stringbuffersize >= 22)
569 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d:%d", a[0], a[1], a[2], a[3], address->port);
575 if (stringbuffersize >= 16)
577 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
583 case LHNETADDRESSTYPE_INET6:
584 a = (const unsigned char *)(&address->addr.in6.sin6_addr);
587 if (stringbuffersize >= 88)
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);
595 if (stringbuffersize >= 80)
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]);
607 int LHNETADDRESS_GetAddressType(const lhnetaddress_t *address)
610 return address->addresstype;
612 return LHNETADDRESSTYPE_NONE;
615 const char *LHNETADDRESS_GetInterfaceName(const lhnetaddress_t *vaddress, char *ifname, size_t ifnamelength)
618 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
620 if (address && address->addresstype == LHNETADDRESSTYPE_INET6)
624 if (if_indextoname(address->addr.in6.sin6_scope_id, ifname) == ifname)
629 // The Win32 API doesn't have if_indextoname() until Windows Vista,
630 // but luckily it just uses the interface ID as the interface name
632 if (dpsnprintf(ifname, ifnamelength, "%lu", address->addr.in6.sin6_scope_id) > 0)
642 int LHNETADDRESS_GetPort(const lhnetaddress_t *address)
646 return address->port;
649 int LHNETADDRESS_SetPort(lhnetaddress_t *vaddress, int port)
651 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
654 address->port = port;
655 switch(address->addresstype)
657 case LHNETADDRESSTYPE_LOOP:
659 case LHNETADDRESSTYPE_INET4:
660 address->addr.in.sin_port = htons((unsigned short)port);
663 case LHNETADDRESSTYPE_INET6:
664 address->addr.in6.sin6_port = htons((unsigned short)port);
672 int LHNETADDRESS_Compare(const lhnetaddress_t *vaddress1, const lhnetaddress_t *vaddress2)
674 lhnetaddressnative_t *address1 = (lhnetaddressnative_t *)vaddress1;
675 lhnetaddressnative_t *address2 = (lhnetaddressnative_t *)vaddress2;
676 if (!address1 || !address2)
678 if (address1->addresstype != address2->addresstype)
680 switch(address1->addresstype)
682 case LHNETADDRESSTYPE_LOOP:
683 if (address1->port != address2->port)
686 case LHNETADDRESSTYPE_INET4:
687 if (address1->addr.in.sin_family != address2->addr.in.sin_family)
689 if (memcmp(&address1->addr.in.sin_addr, &address2->addr.in.sin_addr, sizeof(address1->addr.in.sin_addr)))
691 if (address1->port != address2->port)
695 case LHNETADDRESSTYPE_INET6:
696 if (address1->addr.in6.sin6_family != address2->addr.in6.sin6_family)
698 if (memcmp(&address1->addr.in6.sin6_addr, &address2->addr.in6.sin6_addr, sizeof(address1->addr.in6.sin6_addr)))
700 if (address1->port != address2->port)
709 typedef struct lhnetpacket_s
716 #ifndef STANDALONETEST
717 double sentdoubletime;
719 struct lhnetpacket_s *next, *prev;
723 static int lhnet_active;
724 static lhnetsocket_t lhnet_socketlist;
725 static lhnetpacket_t lhnet_packetlist;
727 static int lhnet_didWSAStartup = 0;
728 static WSADATA lhnet_winsockdata;
731 void LHNET_Init(void)
735 lhnet_socketlist.next = lhnet_socketlist.prev = &lhnet_socketlist;
736 lhnet_packetlist.next = lhnet_packetlist.prev = &lhnet_packetlist;
739 lhnet_didWSAStartup = !WSAStartup(MAKEWORD(1, 1), &lhnet_winsockdata);
740 if (!lhnet_didWSAStartup)
741 Con_Print("LHNET_Init: WSAStartup failed, networking disabled\n");
745 void LHNET_Shutdown(void)
750 while (lhnet_socketlist.next != &lhnet_socketlist)
751 LHNET_CloseSocket(lhnet_socketlist.next);
752 while (lhnet_packetlist.next != &lhnet_packetlist)
754 p = lhnet_packetlist.next;
755 p->prev->next = p->next;
756 p->next->prev = p->prev;
760 if (lhnet_didWSAStartup)
762 lhnet_didWSAStartup = 0;
769 static const char *LHNETPRIVATE_StrError(void)
772 int i = WSAGetLastError();
775 case WSAEINTR: return "WSAEINTR";
776 case WSAEBADF: return "WSAEBADF";
777 case WSAEACCES: return "WSAEACCES";
778 case WSAEFAULT: return "WSAEFAULT";
779 case WSAEINVAL: return "WSAEINVAL";
780 case WSAEMFILE: return "WSAEMFILE";
781 case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK";
782 case WSAEINPROGRESS: return "WSAEINPROGRESS";
783 case WSAEALREADY: return "WSAEALREADY";
784 case WSAENOTSOCK: return "WSAENOTSOCK";
785 case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ";
786 case WSAEMSGSIZE: return "WSAEMSGSIZE";
787 case WSAEPROTOTYPE: return "WSAEPROTOTYPE";
788 case WSAENOPROTOOPT: return "WSAENOPROTOOPT";
789 case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
790 case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
791 case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP";
792 case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT";
793 case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT";
794 case WSAEADDRINUSE: return "WSAEADDRINUSE";
795 case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL";
796 case WSAENETDOWN: return "WSAENETDOWN";
797 case WSAENETUNREACH: return "WSAENETUNREACH";
798 case WSAENETRESET: return "WSAENETRESET";
799 case WSAECONNABORTED: return "WSAECONNABORTED";
800 case WSAECONNRESET: return "WSAECONNRESET";
801 case WSAENOBUFS: return "WSAENOBUFS";
802 case WSAEISCONN: return "WSAEISCONN";
803 case WSAENOTCONN: return "WSAENOTCONN";
804 case WSAESHUTDOWN: return "WSAESHUTDOWN";
805 case WSAETOOMANYREFS: return "WSAETOOMANYREFS";
806 case WSAETIMEDOUT: return "WSAETIMEDOUT";
807 case WSAECONNREFUSED: return "WSAECONNREFUSED";
808 case WSAELOOP: return "WSAELOOP";
809 case WSAENAMETOOLONG: return "WSAENAMETOOLONG";
810 case WSAEHOSTDOWN: return "WSAEHOSTDOWN";
811 case WSAEHOSTUNREACH: return "WSAEHOSTUNREACH";
812 case WSAENOTEMPTY: return "WSAENOTEMPTY";
813 case WSAEPROCLIM: return "WSAEPROCLIM";
814 case WSAEUSERS: return "WSAEUSERS";
815 case WSAEDQUOT: return "WSAEDQUOT";
816 case WSAESTALE: return "WSAESTALE";
817 case WSAEREMOTE: return "WSAEREMOTE";
818 case WSAEDISCON: return "WSAEDISCON";
819 case 0: return "no error";
820 default: return "unknown WSAE error";
823 return strerror(errno);
827 void LHNET_SleepUntilPacket_Microseconds(int microseconds)
836 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
838 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
840 if (lastfd < s->inetsocket)
841 lastfd = s->inetsocket;
842 #if defined(WIN32) && !defined(_MSC_VER)
843 FD_SET((int)s->inetsocket, &fdreadset);
845 FD_SET((unsigned int)s->inetsocket, &fdreadset);
849 tv.tv_sec = microseconds / 1000000;
850 tv.tv_usec = microseconds % 1000000;
851 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
853 Sys_Sleep(microseconds);
857 lhnetsocket_t *LHNET_OpenSocket_Connectionless(lhnetaddress_t *address)
859 lhnetsocket_t *lhnetsocket, *s;
862 lhnetsocket = (lhnetsocket_t *)Z_Malloc(sizeof(*lhnetsocket));
865 memset(lhnetsocket, 0, sizeof(*lhnetsocket));
866 lhnetsocket->address = *address;
867 switch(lhnetsocket->address.addresstype)
869 case LHNETADDRESSTYPE_LOOP:
870 if (lhnetsocket->address.port == 0)
872 // allocate a port dynamically
873 // this search will always terminate because there is never
874 // an allocated socket with port 0, so if the number wraps it
875 // will find the port is unused, and then refuse to use port
876 // 0, causing an intentional failure condition
877 lhnetsocket->address.port = 1024;
880 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
881 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
883 if (s == &lhnet_socketlist)
885 lhnetsocket->address.port++;
888 // check if the port is available
889 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
890 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
892 if (s == &lhnet_socketlist && lhnetsocket->address.port != 0)
894 lhnetsocket->next = &lhnet_socketlist;
895 lhnetsocket->prev = lhnetsocket->next->prev;
896 lhnetsocket->next->prev = lhnetsocket;
897 lhnetsocket->prev->next = lhnetsocket;
901 case LHNETADDRESSTYPE_INET4:
903 case LHNETADDRESSTYPE_INET6:
906 if (lhnet_didWSAStartup)
910 if ((lhnetsocket->inetsocket = socket(address->addresstype == LHNETADDRESSTYPE_INET6 ? PF_INET6 : PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1)
912 if ((lhnetsocket->inetsocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1)
926 if (ioctlsocket(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
930 // We need to set this flag to tell the OS that we only listen on IPv6. If we don't
931 // most OSes will create a dual-protocol socket that also listens on IPv4. In this case
932 // if an IPv4 socket is already bound to the port we want, our bind() call will fail.
934 if (address->addresstype != LHNETADDRESSTYPE_INET6
935 || setsockopt (lhnetsocket->inetsocket, IPPROTO_IPV6, IPV6_V6ONLY,
936 (const char *)&ipv6_only, sizeof(ipv6_only)) == 0
938 // The Win32 API only supports IPV6_V6ONLY since Windows Vista, but fortunately
939 // the default value is what we want on Win32 anyway (IPV6_V6ONLY = true)
940 || SOCKETERRNO == WSAENOPROTOOPT
945 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
949 #if defined(SOL_RFC1149) && defined(RFC1149_1149ONLY)
950 // we got reports of massive lags when this protocol was chosen as transport
951 // so better turn it off
954 int rfc1149enabled = 0;
955 if(setsockopt(lhnetsocket->inetsocket, SOL_RFC1149, RFC1149_1149ONLY, &rfc1149only))
956 Con_Printf("LHNET_OpenSocket_Connectionless: warning: setsockopt(RFC1149_1149ONLY) returned error: %s\n", LHNETPRIVATE_StrError());
957 if(setsockopt(lhnetsocket->inetsocket, SOL_RFC1149, RFC1149_ENABLED, &rfc1149enabled))
958 Con_Printf("LHNET_OpenSocket_Connectionless: warning: setsockopt(RFC1149_ENABLED) returned error: %s\n", LHNETPRIVATE_StrError());
963 if (address->addresstype == LHNETADDRESSTYPE_INET6)
965 namelen = sizeof(localaddress->addr.in6);
966 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
967 if (bindresult != -1)
968 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
973 namelen = sizeof(localaddress->addr.in);
974 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
975 if (bindresult != -1)
976 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
978 if (bindresult != -1)
981 // enable broadcast on this socket
982 setsockopt(lhnetsocket->inetsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i));
983 lhnetsocket->next = &lhnet_socketlist;
984 lhnetsocket->prev = lhnetsocket->next->prev;
985 lhnetsocket->next->prev = lhnetsocket;
986 lhnetsocket->prev->next = lhnetsocket;
988 if (ioctlsocket(lhnetsocket->inetsocket, SIO_UDP_CONNRESET, &_false) == -1)
989 Con_DPrintf("LHNET_OpenSocket_Connectionless: ioctlsocket SIO_UDP_CONNRESET returned error: %s\n", LHNETPRIVATE_StrError());
994 Con_Printf("LHNET_OpenSocket_Connectionless: bind returned error: %s\n", LHNETPRIVATE_StrError());
998 Con_Printf("LHNET_OpenSocket_Connectionless: setsockopt(IPV6_V6ONLY) returned error: %s\n", LHNETPRIVATE_StrError());
1002 Con_Printf("LHNET_OpenSocket_Connectionless: ioctlsocket returned error: %s\n", LHNETPRIVATE_StrError());
1003 closesocket(lhnetsocket->inetsocket);
1006 Con_Printf("LHNET_OpenSocket_Connectionless: socket returned error: %s\n", LHNETPRIVATE_StrError());
1010 Con_Print("LHNET_OpenSocket_Connectionless: can't open a socket (WSAStartup failed during LHNET_Init)\n");
1016 Z_Free(lhnetsocket);
1021 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
1025 // unlink from socket list
1026 if (lhnetsocket->next == NULL)
1028 lhnetsocket->next->prev = lhnetsocket->prev;
1029 lhnetsocket->prev->next = lhnetsocket->next;
1030 lhnetsocket->next = NULL;
1031 lhnetsocket->prev = NULL;
1033 // no special close code for loopback, just inet
1034 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1036 closesocket(lhnetsocket->inetsocket);
1038 Z_Free(lhnetsocket);
1042 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
1045 return &sock->address;
1050 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *vaddress)
1052 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
1054 if (!lhnetsocket || !address || !content || maxcontentlength < 1)
1056 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
1059 lhnetpacket_t *p, *pnext;
1060 // scan for any old packets to timeout while searching for a packet
1061 // that is waiting to be delivered to this socket
1062 currenttime = time(NULL);
1063 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
1066 if (p->timeout < currenttime)
1069 p->next->prev = p->prev;
1070 p->prev->next = p->next;
1074 #ifndef STANDALONETEST
1075 if (cl_netlocalping.value && (realtime - cl_netlocalping.value * (1.0 / 2000.0)) < p->sentdoubletime)
1078 if (value == 0 && p->destinationport == lhnetsocket->address.port)
1080 if (p->length <= maxcontentlength)
1082 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
1083 *address = *localaddress;
1084 address->port = p->sourceport;
1085 memcpy(content, p->data, p->length);
1091 p->next->prev = p->prev;
1092 p->prev->next = p->next;
1097 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
1099 SOCKLEN_T inetaddresslength;
1100 address->addresstype = LHNETADDRESSTYPE_NONE;
1101 inetaddresslength = sizeof(address->addr.in);
1102 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, LHNET_RECVFROM_FLAGS, &address->addr.sock, &inetaddresslength);
1105 address->addresstype = LHNETADDRESSTYPE_INET4;
1106 address->port = ntohs(address->addr.in.sin_port);
1111 int e = SOCKETERRNO;
1112 if (e == EWOULDBLOCK)
1117 Con_Print("Connection refused\n");
1120 Con_DPrintf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
1124 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1126 SOCKLEN_T inetaddresslength;
1127 address->addresstype = LHNETADDRESSTYPE_NONE;
1128 inetaddresslength = sizeof(address->addr.in6);
1129 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, LHNET_RECVFROM_FLAGS, &address->addr.sock, &inetaddresslength);
1132 address->addresstype = LHNETADDRESSTYPE_INET6;
1133 address->port = ntohs(address->addr.in6.sin6_port);
1136 else if (value == -1)
1138 int e = SOCKETERRNO;
1139 if (e == EWOULDBLOCK)
1144 Con_Print("Connection refused\n");
1147 Con_DPrintf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
1154 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *vaddress)
1156 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
1158 if (!lhnetsocket || !address || !content || contentlength < 1)
1160 if (lhnetsocket->address.addresstype != address->addresstype)
1162 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
1165 p = (lhnetpacket_t *)Z_Malloc(sizeof(*p) + contentlength);
1166 p->data = (void *)(p + 1);
1167 memcpy(p->data, content, contentlength);
1168 p->length = contentlength;
1169 p->sourceport = lhnetsocket->address.port;
1170 p->destinationport = address->port;
1171 p->timeout = time(NULL) + 10;
1172 p->next = &lhnet_packetlist;
1173 p->prev = p->next->prev;
1176 #ifndef STANDALONETEST
1177 p->sentdoubletime = realtime;
1179 value = contentlength;
1181 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
1183 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, LHNET_SENDTO_FLAGS, (struct sockaddr *)&address->addr.in, sizeof(struct sockaddr_in));
1186 if (SOCKETERRNO == EWOULDBLOCK)
1188 Con_DPrintf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
1192 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1194 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, 0, (struct sockaddr *)&address->addr.in6, sizeof(struct sockaddr_in6));
1197 if (SOCKETERRNO == EWOULDBLOCK)
1199 Con_DPrintf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
1206 #ifdef STANDALONETEST
1207 int main(int argc, char **argv)
1210 char *buffer = "test", buffer2[1024];
1211 int blen = strlen(buffer);
1213 lhnetsocket_t *sock1;
1214 lhnetsocket_t *sock2;
1215 lhnetaddress_t myaddy1;
1216 lhnetaddress_t myaddy2;
1217 lhnetaddress_t myaddy3;
1218 lhnetaddress_t localhostaddy1;
1219 lhnetaddress_t localhostaddy2;
1223 printf("calling LHNET_Init\n");
1226 printf("calling LHNET_FromPort twice to create two local addresses\n");
1227 LHNETADDRESS_FromPort(&myaddy1, LHNETADDRESSTYPE_INET4, 4000);
1228 LHNETADDRESS_FromPort(&myaddy2, LHNETADDRESSTYPE_INET4, 4001);
1229 LHNETADDRESS_FromString(&localhostaddy1, "127.0.0.1", 4000);
1230 LHNETADDRESS_FromString(&localhostaddy2, "127.0.0.1", 4001);
1232 printf("calling LHNET_OpenSocket_Connectionless twice to create two local sockets\n");
1233 sock1 = LHNET_OpenSocket_Connectionless(&myaddy1);
1234 sock2 = LHNET_OpenSocket_Connectionless(&myaddy2);
1236 printf("calling LHNET_Write to send a packet from the first socket to the second socket\n");
1237 test1 = LHNET_Write(sock1, buffer, blen, &localhostaddy2);
1238 printf("sleeping briefly\n");
1244 printf("calling LHNET_Read on the second socket to read the packet sent from the first socket\n");
1245 test2 = LHNET_Read(sock2, buffer2, b2len - 1, &myaddy3);
1247 Con_Printf("socket to socket test succeeded\n");
1249 Con_Printf("socket to socket test failed\n");
1252 printf("press any key to exit\n");
1256 printf("calling LHNET_Shutdown\n");
1258 printf("exiting\n");
1261 lhnetsocket_t *sock[16], *sendsock;
1270 int sendmessagelength;
1271 lhnetaddress_t destaddress;
1272 lhnetaddress_t receiveaddress;
1273 lhnetaddress_t sockaddress[16];
1274 char buffer[1536], addressstring[128], addressstring2[128];
1275 if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
1277 printf("calling LHNET_Init()\n");
1281 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
1282 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
1283 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
1287 sendmessagelength = 0;
1289 for (i = 0;i < numsockets;i++)
1291 LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
1292 printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
1293 if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
1295 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1296 printf("opened socket successfully (address \"%s\")\n", addressstring2);
1300 printf("failed to open socket\n");
1311 count = atoi(argv[2]);
1312 if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
1314 sendmessage = argv[4];
1315 sendmessagelength = strlen(sendmessage);
1317 for (i = 0;i < numsockets;i++)
1318 if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
1320 if (sendsock == NULL)
1322 printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
1328 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
1332 printf("started, now listening for \"exit\" on the opened sockets\n");
1333 oldtime = time(NULL);
1341 for (i = 0;i < numsockets;i++)
1345 length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
1347 printf("localsock read error: length < 0");
1348 else if (length > 0 && length < (int)sizeof(buffer))
1351 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
1352 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1353 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
1354 if (!strcmp(buffer, "exit"))
1361 if (argc == 5 && count > 0)
1363 newtime = time(NULL);
1364 if (newtime != oldtime)
1366 LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
1367 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
1368 printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
1369 length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
1370 if (length == sendmessagelength)
1371 printf("sent successfully\n");
1373 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
1377 printf("Done sending, still listening for \"exit\"\n");
1381 for (i = 0;i < numsockets;i++)
1385 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1386 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
1387 LHNET_CloseSocket(sock[i]);
1390 printf("calling LHNET_Shutdown()\n");
1394 printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");