2 // Written by Forest Hale 2003-06-15 and placed into public domain.
6 // Windows XP or higher is required for getaddrinfo, but the inclusion of wspiapi provides fallbacks for older versions
7 # define _WIN32_WINNT 0x0501
16 #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
84 typedef struct lhnetaddressnative_s
86 lhnetaddresstype_t addresstype;
91 struct sockaddr_in in;
92 struct sockaddr_in6 in6;
98 // to make LHNETADDRESS_FromString resolve repeated hostnames faster, cache them
99 #define MAX_NAMECACHE 64
100 static struct namecache_s
102 lhnetaddressnative_t address;
103 double expirationtime;
106 namecache[MAX_NAMECACHE];
107 static int namecacheposition = 0;
109 int LHNETADDRESS_FromPort(lhnetaddress_t *vaddress, lhnetaddresstype_t addresstype, int port)
111 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
118 case LHNETADDRESSTYPE_LOOP:
119 // local:port (loopback)
120 memset(address, 0, sizeof(*address));
121 address->addresstype = LHNETADDRESSTYPE_LOOP;
122 address->port = port;
124 case LHNETADDRESSTYPE_INET4:
125 // 0.0.0.0:port (INADDR_ANY, binds to all interfaces)
126 memset(address, 0, sizeof(*address));
127 address->addresstype = LHNETADDRESSTYPE_INET4;
128 address->port = port;
129 address->addr.in.sin_family = AF_INET;
130 address->addr.in.sin_port = htons((unsigned short)port);
132 case LHNETADDRESSTYPE_INET6:
133 // [0:0:0:0:0:0:0:0]:port (IN6ADDR_ANY, binds to all interfaces)
134 memset(address, 0, sizeof(*address));
135 address->addresstype = LHNETADDRESSTYPE_INET6;
136 address->port = port;
137 address->addr.in6.sin6_family = AF_INET6;
138 address->addr.in6.sin6_port = htons((unsigned short)port);
145 int LHNETADDRESS_Resolve(lhnetaddressnative_t *address, const char *name, int port)
148 struct addrinfo hints;
149 struct addrinfo* addrinf;
152 dpsnprintf (port_buff, sizeof (port_buff), "%d", port);
153 port_buff[sizeof (port_buff) - 1] = '\0';
155 memset(&hints, 0, sizeof (hints));
156 hints.ai_family = AF_UNSPEC;
157 hints.ai_socktype = SOCK_DGRAM;
158 //hints.ai_flags = AI_PASSIVE;
160 err = getaddrinfo(name, port_buff, &hints, &addrinf);
161 if (err != 0 || addrinf == NULL)
163 if (addrinf->ai_addr->sa_family != AF_INET6 && addrinf->ai_addr->sa_family != AF_INET)
165 freeaddrinfo (addrinf);
170 if (addrinf->ai_addr->sa_family == AF_INET6)
172 address->addresstype = LHNETADDRESSTYPE_INET6;
173 memcpy(&address->addr.in6, addrinf->ai_addr, sizeof(address->addr.in6));
177 address->addresstype = LHNETADDRESSTYPE_INET4;
178 memcpy(&address->addr.in, addrinf->ai_addr, sizeof(address->addr.in));
180 address->port = port;
182 freeaddrinfo (addrinf);
186 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
188 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
189 int i, port, d1, d2, d3, d4, resolved;
193 #ifdef STANDALONETEST
196 const char* addr_start;
197 const char* addr_end = NULL;
198 const char* port_name = NULL;
199 int addr_family = AF_UNSPEC;
201 if (!address || !string || !*string)
203 memset(address, 0, sizeof(*address));
204 address->addresstype = LHNETADDRESSTYPE_NONE;
207 // If it's a bracketed IPv6 address
208 if (string[0] == '[')
210 const char* end_bracket = strchr(string, ']');
212 if (end_bracket == NULL)
215 if (end_bracket[1] == ':')
216 port_name = end_bracket + 2;
217 else if (end_bracket[1] != '\0')
220 addr_family = AF_INET6;
221 addr_start = &string[1];
222 addr_end = end_bracket;
226 const char* first_colon;
230 // If it's a numeric non-bracket IPv6 address (-> no port),
231 // or it's a numeric IPv4 address, or a name, with a port
232 first_colon = strchr(string, ':');
233 if (first_colon != NULL)
235 const char* last_colon = strrchr(first_colon + 1, ':');
237 // If it's an numeric IPv4 address, or a name, with a port
238 if (last_colon == NULL)
240 addr_end = first_colon;
241 port_name = first_colon + 1;
244 addr_family = AF_INET6;
248 if (addr_end != NULL)
249 namelen = addr_end - addr_start;
251 namelen = strlen (addr_start);
253 if (namelen >= sizeof(name))
254 namelen = sizeof(name) - 1;
255 memcpy (name, addr_start, namelen);
259 port = atoi(port_name);
265 if (!strcmp(name, "local"))
267 address->addresstype = LHNETADDRESSTYPE_LOOP;
268 address->port = port;
271 // try to parse as dotted decimal ipv4 address first
272 // note this supports partial ip addresses
273 d1 = d2 = d3 = d4 = 0;
275 #define sscanf sscanf_s
277 if (addr_family != AF_INET6 &&
278 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)
280 // parsed a valid ipv4 address
281 address->addresstype = LHNETADDRESSTYPE_INET4;
282 address->port = port;
283 address->addr.in.sin_family = AF_INET;
284 address->addr.in.sin_port = htons((unsigned short)port);
285 a = (unsigned char *)&address->addr.in.sin_addr;
290 #ifdef STANDALONETEST
291 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
292 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %s\n", string, string2);
296 for (i = 0;i < MAX_NAMECACHE;i++)
297 if (!strcmp(namecache[i].name, name))
299 #ifdef STANDALONETEST
300 if (i < MAX_NAMECACHE)
302 if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
305 *address = namecache[i].address;
306 address->port = port;
307 if (address->addresstype == LHNETADDRESSTYPE_INET6)
309 address->addr.in6.sin6_port = htons((unsigned short)port);
312 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
314 address->addr.in.sin_port = htons((unsigned short)port);
320 for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
321 namecache[namecacheposition].name[i] = name[i];
322 namecache[namecacheposition].name[i] = 0;
323 #ifndef STANDALONETEST
324 namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
327 // try resolving the address (handles dns and other ip formats)
328 resolved = LHNETADDRESS_Resolve(address, name, port);
331 #ifdef STANDALONETEST
332 const char *protoname;
334 switch (address->addresstype)
336 case LHNETADDRESSTYPE_INET6:
339 case LHNETADDRESSTYPE_INET4:
343 protoname = "UNKNOWN";
346 LHNETADDRESS_ToString(vaddress, string2, sizeof(string2), 1);
347 Con_Printf("LHNETADDRESS_Resolve(\"%s\") returned %s address %s\n", string, protoname, string2);
349 namecache[namecacheposition].address = *address;
353 #ifdef STANDALONETEST
354 printf("name resolution failed on address \"%s\"\n", name);
356 namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
359 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
363 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
365 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
366 int i, port, namelen, d1, d2, d3, d4;
367 struct hostent *hostentry;
371 #ifdef STANDALONETEST
374 if (!address || !string || !*string)
376 memset(address, 0, sizeof(*address));
377 address->addresstype = LHNETADDRESSTYPE_NONE;
379 colon = strrchr(string, ':');
381 port = atoi(colon + 1);
383 colon = string + strlen(string);
386 namelen = colon - string;
389 if (string[0] == '[' && namelen > 0 && string[namelen-1] == ']') // ipv6
394 memcpy(name, string, namelen);
397 if (!strcmp(name, "local"))
399 address->addresstype = LHNETADDRESSTYPE_LOOP;
400 address->port = port;
403 // try to parse as dotted decimal ipv4 address first
404 // note this supports partial ip addresses
405 d1 = d2 = d3 = d4 = 0;
407 #define sscanf sscanf_s
409 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)
411 // parsed a valid ipv4 address
412 address->addresstype = LHNETADDRESSTYPE_INET4;
413 address->port = port;
414 address->addr.in.sin_family = AF_INET;
415 address->addr.in.sin_port = htons((unsigned short)port);
416 a = (unsigned char *)&address->addr.in.sin_addr;
421 #ifdef STANDALONETEST
422 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
423 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %s\n", string, string2);
427 for (i = 0;i < MAX_NAMECACHE;i++)
428 if (!strcmp(namecache[i].name, name))
430 #ifdef STANDALONETEST
431 if (i < MAX_NAMECACHE)
433 if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
436 *address = namecache[i].address;
437 address->port = port;
438 if (address->addresstype == LHNETADDRESSTYPE_INET6)
440 address->addr.in6.sin6_port = htons((unsigned short)port);
443 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
445 address->addr.in.sin_port = htons((unsigned short)port);
450 // try gethostbyname (handles dns and other ip formats)
451 hostentry = gethostbyname(name);
454 if (hostentry->h_addrtype == AF_INET6)
457 address->addresstype = LHNETADDRESSTYPE_INET6;
458 address->port = port;
459 address->addr.in6.sin6_family = hostentry->h_addrtype;
460 address->addr.in6.sin6_port = htons((unsigned short)port);
461 memcpy(&address->addr.in6.sin6_addr, hostentry->h_addr_list[0], sizeof(address->addr.in6.sin6_addr));
462 for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
463 namecache[namecacheposition].name[i] = name[i];
464 namecache[namecacheposition].name[i] = 0;
465 #ifndef STANDALONETEST
466 namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
468 namecache[namecacheposition].address = *address;
469 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
470 #ifdef STANDALONETEST
471 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
472 printf("gethostbyname(\"%s\") returned ipv6 address %s\n", string, string2);
476 else if (hostentry->h_addrtype == AF_INET)
479 address->addresstype = LHNETADDRESSTYPE_INET4;
480 address->port = port;
481 address->addr.in.sin_family = hostentry->h_addrtype;
482 address->addr.in.sin_port = htons((unsigned short)port);
483 memcpy(&address->addr.in.sin_addr, hostentry->h_addr_list[0], sizeof(address->addr.in.sin_addr));
484 for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
485 namecache[namecacheposition].name[i] = name[i];
486 namecache[namecacheposition].name[i] = 0;
487 #ifndef STANDALONETEST
488 namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
490 namecache[namecacheposition].address = *address;
491 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
492 #ifdef STANDALONETEST
493 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
494 printf("gethostbyname(\"%s\") returned ipv4 address %s\n", string, string2);
499 #ifdef STANDALONETEST
500 printf("gethostbyname failed on address \"%s\"\n", name);
502 for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
503 namecache[namecacheposition].name[i] = name[i];
504 namecache[namecacheposition].name[i] = 0;
505 #ifndef STANDALONETEST
506 namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
508 namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
509 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
514 int LHNETADDRESS_ToString(const lhnetaddress_t *vaddress, char *string, int stringbuffersize, int includeport)
516 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
517 const unsigned char *a;
519 if (!address || !string || stringbuffersize < 1)
521 switch(address->addresstype)
525 case LHNETADDRESSTYPE_LOOP:
528 if (stringbuffersize >= 12)
530 dpsnprintf(string, stringbuffersize, "local:%d", address->port);
536 if (stringbuffersize >= 6)
538 memcpy(string, "local", 6);
543 case LHNETADDRESSTYPE_INET4:
544 a = (const unsigned char *)(&address->addr.in.sin_addr);
547 if (stringbuffersize >= 22)
549 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d:%d", a[0], a[1], a[2], a[3], address->port);
555 if (stringbuffersize >= 16)
557 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
562 case LHNETADDRESSTYPE_INET6:
563 a = (const unsigned char *)(&address->addr.in6.sin6_addr);
566 if (stringbuffersize >= 88)
568 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);
574 if (stringbuffersize >= 80)
576 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]);
585 int LHNETADDRESS_GetAddressType(const lhnetaddress_t *address)
588 return address->addresstype;
590 return LHNETADDRESSTYPE_NONE;
593 const char *LHNETADDRESS_GetInterfaceName(const lhnetaddress_t *vaddress)
596 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
598 if (address && address->addresstype == LHNETADDRESSTYPE_INET6)
602 static char ifname [IF_NAMESIZE];
604 if (if_indextoname(address->addr.in6.sin6_scope_id, ifname) == ifname)
609 // The Win32 API doesn't have if_indextoname() until Windows Vista,
610 // but luckily it just uses the interface ID as the interface name
612 static char ifname [16];
614 if (dpsnprintf(ifname, sizeof(ifname), "%lu", address->addr.in6.sin6_scope_id) > 0)
624 int LHNETADDRESS_GetPort(const lhnetaddress_t *address)
628 return address->port;
631 int LHNETADDRESS_SetPort(lhnetaddress_t *vaddress, int port)
633 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
636 address->port = port;
637 switch(address->addresstype)
639 case LHNETADDRESSTYPE_LOOP:
641 case LHNETADDRESSTYPE_INET4:
642 address->addr.in.sin_port = htons((unsigned short)port);
644 case LHNETADDRESSTYPE_INET6:
645 address->addr.in6.sin6_port = htons((unsigned short)port);
652 int LHNETADDRESS_Compare(const lhnetaddress_t *vaddress1, const lhnetaddress_t *vaddress2)
654 lhnetaddressnative_t *address1 = (lhnetaddressnative_t *)vaddress1;
655 lhnetaddressnative_t *address2 = (lhnetaddressnative_t *)vaddress2;
656 if (!address1 || !address2)
658 if (address1->addresstype != address2->addresstype)
660 switch(address1->addresstype)
662 case LHNETADDRESSTYPE_LOOP:
663 if (address1->port != address2->port)
666 case LHNETADDRESSTYPE_INET4:
667 if (address1->addr.in.sin_family != address2->addr.in.sin_family)
669 if (memcmp(&address1->addr.in.sin_addr, &address2->addr.in.sin_addr, sizeof(address1->addr.in.sin_addr)))
671 if (address1->port != address2->port)
674 case LHNETADDRESSTYPE_INET6:
675 if (address1->addr.in6.sin6_family != address2->addr.in6.sin6_family)
677 if (memcmp(&address1->addr.in6.sin6_addr, &address2->addr.in6.sin6_addr, sizeof(address1->addr.in6.sin6_addr)))
679 if (address1->port != address2->port)
687 typedef struct lhnetpacket_s
694 #ifndef STANDALONETEST
695 double sentdoubletime;
697 struct lhnetpacket_s *next, *prev;
701 static int lhnet_active;
702 static lhnetsocket_t lhnet_socketlist;
703 static lhnetpacket_t lhnet_packetlist;
705 static int lhnet_didWSAStartup = 0;
706 static WSADATA lhnet_winsockdata;
709 void LHNET_Init(void)
713 lhnet_socketlist.next = lhnet_socketlist.prev = &lhnet_socketlist;
714 lhnet_packetlist.next = lhnet_packetlist.prev = &lhnet_packetlist;
717 lhnet_didWSAStartup = !WSAStartup(MAKEWORD(1, 1), &lhnet_winsockdata);
718 if (!lhnet_didWSAStartup)
719 Con_Print("LHNET_Init: WSAStartup failed, networking disabled\n");
723 void LHNET_Shutdown(void)
728 while (lhnet_socketlist.next != &lhnet_socketlist)
729 LHNET_CloseSocket(lhnet_socketlist.next);
730 while (lhnet_packetlist.next != &lhnet_packetlist)
732 p = lhnet_packetlist.next;
733 p->prev->next = p->next;
734 p->next->prev = p->prev;
738 if (lhnet_didWSAStartup)
740 lhnet_didWSAStartup = 0;
747 static const char *LHNETPRIVATE_StrError(void)
750 int i = WSAGetLastError();
753 case WSAEINTR: return "WSAEINTR";
754 case WSAEBADF: return "WSAEBADF";
755 case WSAEACCES: return "WSAEACCES";
756 case WSAEFAULT: return "WSAEFAULT";
757 case WSAEINVAL: return "WSAEINVAL";
758 case WSAEMFILE: return "WSAEMFILE";
759 case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK";
760 case WSAEINPROGRESS: return "WSAEINPROGRESS";
761 case WSAEALREADY: return "WSAEALREADY";
762 case WSAENOTSOCK: return "WSAENOTSOCK";
763 case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ";
764 case WSAEMSGSIZE: return "WSAEMSGSIZE";
765 case WSAEPROTOTYPE: return "WSAEPROTOTYPE";
766 case WSAENOPROTOOPT: return "WSAENOPROTOOPT";
767 case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
768 case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
769 case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP";
770 case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT";
771 case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT";
772 case WSAEADDRINUSE: return "WSAEADDRINUSE";
773 case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL";
774 case WSAENETDOWN: return "WSAENETDOWN";
775 case WSAENETUNREACH: return "WSAENETUNREACH";
776 case WSAENETRESET: return "WSAENETRESET";
777 case WSAECONNABORTED: return "WSAECONNABORTED";
778 case WSAECONNRESET: return "WSAECONNRESET";
779 case WSAENOBUFS: return "WSAENOBUFS";
780 case WSAEISCONN: return "WSAEISCONN";
781 case WSAENOTCONN: return "WSAENOTCONN";
782 case WSAESHUTDOWN: return "WSAESHUTDOWN";
783 case WSAETOOMANYREFS: return "WSAETOOMANYREFS";
784 case WSAETIMEDOUT: return "WSAETIMEDOUT";
785 case WSAECONNREFUSED: return "WSAECONNREFUSED";
786 case WSAELOOP: return "WSAELOOP";
787 case WSAENAMETOOLONG: return "WSAENAMETOOLONG";
788 case WSAEHOSTDOWN: return "WSAEHOSTDOWN";
789 case WSAEHOSTUNREACH: return "WSAEHOSTUNREACH";
790 case WSAENOTEMPTY: return "WSAENOTEMPTY";
791 case WSAEPROCLIM: return "WSAEPROCLIM";
792 case WSAEUSERS: return "WSAEUSERS";
793 case WSAEDQUOT: return "WSAEDQUOT";
794 case WSAESTALE: return "WSAESTALE";
795 case WSAEREMOTE: return "WSAEREMOTE";
796 case WSAEDISCON: return "WSAEDISCON";
797 case 0: return "no error";
798 default: return "unknown WSAE error";
801 return strerror(errno);
805 void LHNET_SleepUntilPacket_Microseconds(int microseconds)
813 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
815 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
817 if (lastfd < s->inetsocket)
818 lastfd = s->inetsocket;
819 FD_SET((unsigned int)s->inetsocket, &fdreadset);
822 tv.tv_sec = microseconds / 1000000;
823 tv.tv_usec = microseconds % 1000000;
824 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
827 lhnetsocket_t *LHNET_OpenSocket_Connectionless(lhnetaddress_t *address)
829 lhnetsocket_t *lhnetsocket, *s;
832 lhnetsocket = (lhnetsocket_t *)Z_Malloc(sizeof(*lhnetsocket));
835 memset(lhnetsocket, 0, sizeof(*lhnetsocket));
836 lhnetsocket->address = *address;
837 switch(lhnetsocket->address.addresstype)
839 case LHNETADDRESSTYPE_LOOP:
840 if (lhnetsocket->address.port == 0)
842 // allocate a port dynamically
843 // this search will always terminate because there is never
844 // an allocated socket with port 0, so if the number wraps it
845 // will find the port is unused, and then refuse to use port
846 // 0, causing an intentional failure condition
847 lhnetsocket->address.port = 1024;
850 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
851 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
853 if (s == &lhnet_socketlist)
855 lhnetsocket->address.port++;
858 // check if the port is available
859 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
860 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
862 if (s == &lhnet_socketlist && lhnetsocket->address.port != 0)
864 lhnetsocket->next = &lhnet_socketlist;
865 lhnetsocket->prev = lhnetsocket->next->prev;
866 lhnetsocket->next->prev = lhnetsocket;
867 lhnetsocket->prev->next = lhnetsocket;
871 case LHNETADDRESSTYPE_INET4:
872 case LHNETADDRESSTYPE_INET6:
874 if (lhnet_didWSAStartup)
877 if ((lhnetsocket->inetsocket = socket(address->addresstype == LHNETADDRESSTYPE_INET6 ? PF_INET6 : PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1)
885 if (ioctlsocket(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
888 // We need to set this flag to tell the OS that we only listen on IPv6. If we don't
889 // most OSes will create a dual-protocol socket that also listens on IPv4. In this case
890 // if an IPv4 socket is already bound to the port we want, our bind() call will fail.
892 if (address->addresstype != LHNETADDRESSTYPE_INET6
893 || setsockopt (lhnetsocket->inetsocket, IPPROTO_IPV6, IPV6_V6ONLY,
894 (const char *)&ipv6_only, sizeof(ipv6_only)) == 0
896 // The Win32 API only supports IPV6_V6ONLY since Windows Vista, but fortunately
897 // the default value is what we want on Win32 anyway (IPV6_V6ONLY = true)
898 || SOCKETERRNO == WSAENOPROTOOPT
903 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
906 if (address->addresstype == LHNETADDRESSTYPE_INET6)
908 namelen = sizeof(localaddress->addr.in6);
909 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
910 if (bindresult != -1)
911 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
915 namelen = sizeof(localaddress->addr.in);
916 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
917 if (bindresult != -1)
918 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
920 if (bindresult != -1)
923 // enable broadcast on this socket
924 setsockopt(lhnetsocket->inetsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i));
925 lhnetsocket->next = &lhnet_socketlist;
926 lhnetsocket->prev = lhnetsocket->next->prev;
927 lhnetsocket->next->prev = lhnetsocket;
928 lhnetsocket->prev->next = lhnetsocket;
930 if (ioctlsocket(lhnetsocket->inetsocket, SIO_UDP_CONNRESET, &_false) == -1)
931 Con_DPrintf("LHNET_OpenSocket_Connectionless: ioctlsocket SIO_UDP_CONNRESET returned error: %s\n", LHNETPRIVATE_StrError());
936 Con_Printf("LHNET_OpenSocket_Connectionless: bind returned error: %s\n", LHNETPRIVATE_StrError());
940 Con_Printf("LHNET_OpenSocket_Connectionless: setsockopt(IPV6_V6ONLY) returned error: %s\n", LHNETPRIVATE_StrError());
944 Con_Printf("LHNET_OpenSocket_Connectionless: ioctlsocket returned error: %s\n", LHNETPRIVATE_StrError());
945 closesocket(lhnetsocket->inetsocket);
948 Con_Printf("LHNET_OpenSocket_Connectionless: socket returned error: %s\n", LHNETPRIVATE_StrError());
952 Con_Print("LHNET_OpenSocket_Connectionless: can't open a socket (WSAStartup failed during LHNET_Init)\n");
963 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
967 // unlink from socket list
968 if (lhnetsocket->next == NULL)
970 lhnetsocket->next->prev = lhnetsocket->prev;
971 lhnetsocket->prev->next = lhnetsocket->next;
972 lhnetsocket->next = NULL;
973 lhnetsocket->prev = NULL;
975 // no special close code for loopback, just inet
976 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
978 closesocket(lhnetsocket->inetsocket);
984 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
987 return &sock->address;
992 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *vaddress)
994 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
996 if (!lhnetsocket || !address || !content || maxcontentlength < 1)
998 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
1001 lhnetpacket_t *p, *pnext;
1002 // scan for any old packets to timeout while searching for a packet
1003 // that is waiting to be delivered to this socket
1004 currenttime = time(NULL);
1005 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
1008 if (p->timeout < currenttime)
1011 p->next->prev = p->prev;
1012 p->prev->next = p->next;
1016 #ifndef STANDALONETEST
1017 if (cl_netlocalping.value && (realtime - cl_netlocalping.value * (1.0 / 2000.0)) < p->sentdoubletime)
1020 if (value == 0 && p->destinationport == lhnetsocket->address.port)
1022 if (p->length <= maxcontentlength)
1024 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
1025 *address = *localaddress;
1026 address->port = p->sourceport;
1027 memcpy(content, p->data, p->length);
1033 p->next->prev = p->prev;
1034 p->prev->next = p->next;
1039 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
1041 SOCKLEN_T inetaddresslength;
1042 address->addresstype = LHNETADDRESSTYPE_NONE;
1043 inetaddresslength = sizeof(address->addr.in);
1044 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, 0, &address->addr.sock, &inetaddresslength);
1047 address->addresstype = LHNETADDRESSTYPE_INET4;
1048 address->port = ntohs(address->addr.in.sin_port);
1051 else if (value == -1)
1053 int e = SOCKETERRNO;
1054 if (e == EWOULDBLOCK)
1059 Con_Print("Connection refused\n");
1062 Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
1065 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1067 SOCKLEN_T inetaddresslength;
1068 address->addresstype = LHNETADDRESSTYPE_NONE;
1069 inetaddresslength = sizeof(address->addr.in6);
1070 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, 0, &address->addr.sock, &inetaddresslength);
1073 address->addresstype = LHNETADDRESSTYPE_INET6;
1074 address->port = ntohs(address->addr.in6.sin6_port);
1077 else if (value == -1)
1079 int e = SOCKETERRNO;
1080 if (e == EWOULDBLOCK)
1085 Con_Print("Connection refused\n");
1088 Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
1094 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *vaddress)
1096 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
1098 if (!lhnetsocket || !address || !content || contentlength < 1)
1100 if (lhnetsocket->address.addresstype != address->addresstype)
1102 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
1105 p = (lhnetpacket_t *)Z_Malloc(sizeof(*p) + contentlength);
1106 p->data = (void *)(p + 1);
1107 memcpy(p->data, content, contentlength);
1108 p->length = contentlength;
1109 p->sourceport = lhnetsocket->address.port;
1110 p->destinationport = address->port;
1111 p->timeout = time(NULL) + 10;
1112 p->next = &lhnet_packetlist;
1113 p->prev = p->next->prev;
1116 #ifndef STANDALONETEST
1117 p->sentdoubletime = realtime;
1119 value = contentlength;
1121 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
1123 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, 0, (struct sockaddr *)&address->addr.in, sizeof(struct sockaddr_in));
1126 if (SOCKETERRNO == EWOULDBLOCK)
1128 Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
1131 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1133 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, 0, (struct sockaddr *)&address->addr.in6, sizeof(struct sockaddr_in6));
1136 if (SOCKETERRNO == EWOULDBLOCK)
1138 Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
1144 #ifdef STANDALONETEST
1145 int main(int argc, char **argv)
1148 char *buffer = "test", buffer2[1024];
1149 int blen = strlen(buffer);
1151 lhnetsocket_t *sock1;
1152 lhnetsocket_t *sock2;
1153 lhnetaddress_t myaddy1;
1154 lhnetaddress_t myaddy2;
1155 lhnetaddress_t myaddy3;
1156 lhnetaddress_t localhostaddy1;
1157 lhnetaddress_t localhostaddy2;
1161 printf("calling LHNET_Init\n");
1164 printf("calling LHNET_FromPort twice to create two local addresses\n");
1165 LHNETADDRESS_FromPort(&myaddy1, LHNETADDRESSTYPE_INET4, 4000);
1166 LHNETADDRESS_FromPort(&myaddy2, LHNETADDRESSTYPE_INET4, 4001);
1167 LHNETADDRESS_FromString(&localhostaddy1, "127.0.0.1", 4000);
1168 LHNETADDRESS_FromString(&localhostaddy2, "127.0.0.1", 4001);
1170 printf("calling LHNET_OpenSocket_Connectionless twice to create two local sockets\n");
1171 sock1 = LHNET_OpenSocket_Connectionless(&myaddy1);
1172 sock2 = LHNET_OpenSocket_Connectionless(&myaddy2);
1174 printf("calling LHNET_Write to send a packet from the first socket to the second socket\n");
1175 test1 = LHNET_Write(sock1, buffer, blen, &localhostaddy2);
1176 printf("sleeping briefly\n");
1182 printf("calling LHNET_Read on the second socket to read the packet sent from the first socket\n");
1183 test2 = LHNET_Read(sock2, buffer2, b2len - 1, &myaddy3);
1185 Con_Printf("socket to socket test succeeded\n");
1187 Con_Printf("socket to socket test failed\n");
1190 printf("press any key to exit\n");
1194 printf("calling LHNET_Shutdown\n");
1196 printf("exiting\n");
1199 lhnetsocket_t *sock[16], *sendsock;
1208 int sendmessagelength;
1209 lhnetaddress_t destaddress;
1210 lhnetaddress_t receiveaddress;
1211 lhnetaddress_t sockaddress[16];
1212 char buffer[1536], addressstring[128], addressstring2[128];
1213 if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
1215 printf("calling LHNET_Init()\n");
1219 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
1220 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
1221 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
1225 sendmessagelength = 0;
1227 for (i = 0;i < numsockets;i++)
1229 LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
1230 printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
1231 if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
1233 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1234 printf("opened socket successfully (address \"%s\")\n", addressstring2);
1238 printf("failed to open socket\n");
1249 count = atoi(argv[2]);
1250 if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
1252 sendmessage = argv[4];
1253 sendmessagelength = strlen(sendmessage);
1255 for (i = 0;i < numsockets;i++)
1256 if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
1258 if (sendsock == NULL)
1260 printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
1266 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
1270 printf("started, now listening for \"exit\" on the opened sockets\n");
1271 oldtime = time(NULL);
1279 for (i = 0;i < numsockets;i++)
1283 length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
1285 printf("localsock read error: length < 0");
1286 else if (length > 0 && length < (int)sizeof(buffer))
1289 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
1290 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1291 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
1292 if (!strcmp(buffer, "exit"))
1299 if (argc == 5 && count > 0)
1301 newtime = time(NULL);
1302 if (newtime != oldtime)
1304 LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
1305 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
1306 printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
1307 length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
1308 if (length == sendmessagelength)
1309 printf("sent successfully\n");
1311 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
1315 printf("Done sending, still listening for \"exit\"\n");
1319 for (i = 0;i < numsockets;i++)
1323 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1324 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
1325 LHNET_CloseSocket(sock[i]);
1328 printf("calling LHNET_Shutdown()\n");
1332 printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");