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
10 # include <ws2tcpip.h>
16 #ifndef STANDALONETEST
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <sys/ioctl.h>
31 #include <netinet/in.h>
32 #include <arpa/inet.h>
39 #include <proto/socket.h>
42 // for Z_Malloc/Z_Free in quake
43 #ifndef STANDALONETEST
48 #define Con_Print printf
49 #define Con_Printf printf
50 #define Z_Malloc malloc
57 #define EWOULDBLOCK WSAEWOULDBLOCK
58 #define ECONNREFUSED WSAECONNREFUSED
60 #define SOCKETERRNO WSAGetLastError()
62 #define IOC_VENDOR 0x18000000
63 #define _WSAIOW(x,y) (IOC_IN|(x)|(y))
64 #define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
67 #elif defined(__MORPHOS__)
68 #define ioctlsocket IoctlSocket
69 #define closesocket CloseSocket
70 #define SOCKETERRNO Errno()
74 #define ioctlsocket ioctl
75 #define closesocket close
76 #define SOCKETERRNO errno
78 #define SOCKLEN_T socklen_t
82 #define LHNET_RECVFROM_FLAGS MSG_DONTWAIT
83 #define LHNET_SENDTO_FLAGS 0
85 #define LHNET_RECVFROM_FLAGS 0
86 #define LHNET_SENDTO_FLAGS 0
89 typedef struct lhnetaddressnative_s
91 lhnetaddresstype_t addresstype;
96 struct sockaddr_in in;
98 struct sockaddr_in6 in6;
103 lhnetaddressnative_t;
105 // to make LHNETADDRESS_FromString resolve repeated hostnames faster, cache them
106 #define MAX_NAMECACHE 64
107 static struct namecache_s
109 lhnetaddressnative_t address;
110 double expirationtime;
113 namecache[MAX_NAMECACHE];
114 static int namecacheposition = 0;
116 int LHNETADDRESS_FromPort(lhnetaddress_t *vaddress, lhnetaddresstype_t addresstype, int port)
118 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
125 case LHNETADDRESSTYPE_LOOP:
126 // local:port (loopback)
127 memset(address, 0, sizeof(*address));
128 address->addresstype = LHNETADDRESSTYPE_LOOP;
129 address->port = port;
131 case LHNETADDRESSTYPE_INET4:
132 // 0.0.0.0:port (INADDR_ANY, binds to all interfaces)
133 memset(address, 0, sizeof(*address));
134 address->addresstype = LHNETADDRESSTYPE_INET4;
135 address->port = port;
136 address->addr.in.sin_family = AF_INET;
137 address->addr.in.sin_port = htons((unsigned short)port);
140 case LHNETADDRESSTYPE_INET6:
141 // [0:0:0:0:0:0:0:0]:port (IN6ADDR_ANY, binds to all interfaces)
142 memset(address, 0, sizeof(*address));
143 address->addresstype = LHNETADDRESSTYPE_INET6;
144 address->port = port;
145 address->addr.in6.sin6_family = AF_INET6;
146 address->addr.in6.sin6_port = htons((unsigned short)port);
154 int LHNETADDRESS_Resolve(lhnetaddressnative_t *address, const char *name, int port)
157 struct addrinfo hints;
158 struct addrinfo* addrinf;
161 dpsnprintf (port_buff, sizeof (port_buff), "%d", port);
162 port_buff[sizeof (port_buff) - 1] = '\0';
164 memset(&hints, 0, sizeof (hints));
165 hints.ai_family = AF_UNSPEC;
166 hints.ai_socktype = SOCK_DGRAM;
167 //hints.ai_flags = AI_PASSIVE;
169 err = getaddrinfo(name, port_buff, &hints, &addrinf);
170 if (err != 0 || addrinf == NULL)
172 if (addrinf->ai_addr->sa_family != AF_INET6 && addrinf->ai_addr->sa_family != AF_INET)
174 freeaddrinfo (addrinf);
179 if (addrinf->ai_addr->sa_family == AF_INET6)
181 address->addresstype = LHNETADDRESSTYPE_INET6;
182 memcpy(&address->addr.in6, addrinf->ai_addr, sizeof(address->addr.in6));
186 address->addresstype = LHNETADDRESSTYPE_INET4;
187 memcpy(&address->addr.in, addrinf->ai_addr, sizeof(address->addr.in));
189 address->port = port;
191 freeaddrinfo (addrinf);
195 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
197 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
198 int i, port, d1, d2, d3, d4, resolved;
202 #ifdef STANDALONETEST
205 const char* addr_start;
206 const char* addr_end = NULL;
207 const char* port_name = NULL;
208 int addr_family = AF_UNSPEC;
210 if (!address || !string || !*string)
212 memset(address, 0, sizeof(*address));
213 address->addresstype = LHNETADDRESSTYPE_NONE;
216 // If it's a bracketed IPv6 address
217 if (string[0] == '[')
219 const char* end_bracket = strchr(string, ']');
221 if (end_bracket == NULL)
224 if (end_bracket[1] == ':')
225 port_name = end_bracket + 2;
226 else if (end_bracket[1] != '\0')
229 addr_family = AF_INET6;
230 addr_start = &string[1];
231 addr_end = end_bracket;
235 const char* first_colon;
239 // If it's a numeric non-bracket IPv6 address (-> no port),
240 // or it's a numeric IPv4 address, or a name, with a port
241 first_colon = strchr(string, ':');
242 if (first_colon != NULL)
244 const char* last_colon = strrchr(first_colon + 1, ':');
246 // If it's an numeric IPv4 address, or a name, with a port
247 if (last_colon == NULL)
249 addr_end = first_colon;
250 port_name = first_colon + 1;
253 addr_family = AF_INET6;
257 if (addr_end != NULL)
258 namelen = addr_end - addr_start;
260 namelen = strlen (addr_start);
262 if (namelen >= sizeof(name))
263 namelen = sizeof(name) - 1;
264 memcpy (name, addr_start, namelen);
268 port = atoi(port_name);
274 if (!strcmp(name, "local"))
276 address->addresstype = LHNETADDRESSTYPE_LOOP;
277 address->port = port;
280 // try to parse as dotted decimal ipv4 address first
281 // note this supports partial ip addresses
282 d1 = d2 = d3 = d4 = 0;
284 #define sscanf sscanf_s
286 if (addr_family != AF_INET6 &&
287 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)
289 // parsed a valid ipv4 address
290 address->addresstype = LHNETADDRESSTYPE_INET4;
291 address->port = port;
292 address->addr.in.sin_family = AF_INET;
293 address->addr.in.sin_port = htons((unsigned short)port);
294 a = (unsigned char *)&address->addr.in.sin_addr;
299 #ifdef STANDALONETEST
300 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
301 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %s\n", string, string2);
305 for (i = 0;i < MAX_NAMECACHE;i++)
306 if (!strcmp(namecache[i].name, name))
308 #ifdef STANDALONETEST
309 if (i < MAX_NAMECACHE)
311 if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
314 *address = namecache[i].address;
315 address->port = port;
316 if (address->addresstype == LHNETADDRESSTYPE_INET6)
318 address->addr.in6.sin6_port = htons((unsigned short)port);
321 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
323 address->addr.in.sin_port = htons((unsigned short)port);
329 for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
330 namecache[namecacheposition].name[i] = name[i];
331 namecache[namecacheposition].name[i] = 0;
332 #ifndef STANDALONETEST
333 namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
336 // try resolving the address (handles dns and other ip formats)
337 resolved = LHNETADDRESS_Resolve(address, name, port);
340 #ifdef STANDALONETEST
341 const char *protoname;
343 switch (address->addresstype)
345 case LHNETADDRESSTYPE_INET6:
348 case LHNETADDRESSTYPE_INET4:
352 protoname = "UNKNOWN";
355 LHNETADDRESS_ToString(vaddress, string2, sizeof(string2), 1);
356 Con_Printf("LHNETADDRESS_Resolve(\"%s\") returned %s address %s\n", string, protoname, string2);
358 namecache[namecacheposition].address = *address;
362 #ifdef STANDALONETEST
363 printf("name resolution failed on address \"%s\"\n", name);
365 namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
368 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
372 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
374 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
375 int i, port, namelen, d1, d2, d3, d4;
376 struct hostent *hostentry;
380 #ifdef STANDALONETEST
383 if (!address || !string || !*string)
385 memset(address, 0, sizeof(*address));
386 address->addresstype = LHNETADDRESSTYPE_NONE;
388 colon = strrchr(string, ':');
390 port = atoi(colon + 1);
392 colon = string + strlen(string);
395 namelen = colon - string;
398 if (string[0] == '[' && namelen > 0 && string[namelen-1] == ']') // ipv6
403 memcpy(name, string, namelen);
406 if (!strcmp(name, "local"))
408 address->addresstype = LHNETADDRESSTYPE_LOOP;
409 address->port = port;
412 // try to parse as dotted decimal ipv4 address first
413 // note this supports partial ip addresses
414 d1 = d2 = d3 = d4 = 0;
416 #define sscanf sscanf_s
418 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)
420 // parsed a valid ipv4 address
421 address->addresstype = LHNETADDRESSTYPE_INET4;
422 address->port = port;
423 address->addr.in.sin_family = AF_INET;
424 address->addr.in.sin_port = htons((unsigned short)port);
425 a = (unsigned char *)&address->addr.in.sin_addr;
430 #ifdef STANDALONETEST
431 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
432 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %s\n", string, string2);
436 for (i = 0;i < MAX_NAMECACHE;i++)
437 if (!strcmp(namecache[i].name, name))
439 #ifdef STANDALONETEST
440 if (i < MAX_NAMECACHE)
442 if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
445 *address = namecache[i].address;
446 address->port = port;
447 if (address->addresstype == LHNETADDRESSTYPE_INET6)
450 address->addr.in6.sin6_port = htons((unsigned short)port);
454 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
456 address->addr.in.sin_port = htons((unsigned short)port);
461 // try gethostbyname (handles dns and other ip formats)
462 hostentry = gethostbyname(name);
465 if (hostentry->h_addrtype == AF_INET6)
469 address->addresstype = LHNETADDRESSTYPE_INET6;
470 address->port = port;
471 address->addr.in6.sin6_family = hostentry->h_addrtype;
472 address->addr.in6.sin6_port = htons((unsigned short)port);
473 memcpy(&address->addr.in6.sin6_addr, hostentry->h_addr_list[0], sizeof(address->addr.in6.sin6_addr));
474 for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
475 namecache[namecacheposition].name[i] = name[i];
476 namecache[namecacheposition].name[i] = 0;
477 #ifndef STANDALONETEST
478 namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
480 namecache[namecacheposition].address = *address;
481 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
482 #ifdef STANDALONETEST
483 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
484 printf("gethostbyname(\"%s\") returned ipv6 address %s\n", string, string2);
489 else if (hostentry->h_addrtype == AF_INET)
492 address->addresstype = LHNETADDRESSTYPE_INET4;
493 address->port = port;
494 address->addr.in.sin_family = hostentry->h_addrtype;
495 address->addr.in.sin_port = htons((unsigned short)port);
496 memcpy(&address->addr.in.sin_addr, hostentry->h_addr_list[0], sizeof(address->addr.in.sin_addr));
497 for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
498 namecache[namecacheposition].name[i] = name[i];
499 namecache[namecacheposition].name[i] = 0;
500 #ifndef STANDALONETEST
501 namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
503 namecache[namecacheposition].address = *address;
504 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
505 #ifdef STANDALONETEST
506 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
507 printf("gethostbyname(\"%s\") returned ipv4 address %s\n", string, string2);
512 #ifdef STANDALONETEST
513 printf("gethostbyname failed on address \"%s\"\n", name);
515 for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
516 namecache[namecacheposition].name[i] = name[i];
517 namecache[namecacheposition].name[i] = 0;
518 #ifndef STANDALONETEST
519 namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
521 namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
522 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
527 int LHNETADDRESS_ToString(const lhnetaddress_t *vaddress, char *string, int stringbuffersize, int includeport)
529 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
530 const unsigned char *a;
532 if (!address || !string || stringbuffersize < 1)
534 switch(address->addresstype)
538 case LHNETADDRESSTYPE_LOOP:
541 if (stringbuffersize >= 12)
543 dpsnprintf(string, stringbuffersize, "local:%d", address->port);
549 if (stringbuffersize >= 6)
551 memcpy(string, "local", 6);
556 case LHNETADDRESSTYPE_INET4:
557 a = (const unsigned char *)(&address->addr.in.sin_addr);
560 if (stringbuffersize >= 22)
562 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d:%d", a[0], a[1], a[2], a[3], address->port);
568 if (stringbuffersize >= 16)
570 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
576 case LHNETADDRESSTYPE_INET6:
577 a = (const unsigned char *)(&address->addr.in6.sin6_addr);
580 if (stringbuffersize >= 88)
582 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);
588 if (stringbuffersize >= 80)
590 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]);
600 int LHNETADDRESS_GetAddressType(const lhnetaddress_t *address)
603 return address->addresstype;
605 return LHNETADDRESSTYPE_NONE;
608 const char *LHNETADDRESS_GetInterfaceName(const lhnetaddress_t *vaddress)
611 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
613 if (address && address->addresstype == LHNETADDRESSTYPE_INET6)
617 static char ifname [IF_NAMESIZE];
619 if (if_indextoname(address->addr.in6.sin6_scope_id, ifname) == ifname)
624 // The Win32 API doesn't have if_indextoname() until Windows Vista,
625 // but luckily it just uses the interface ID as the interface name
627 static char ifname [16];
629 if (dpsnprintf(ifname, sizeof(ifname), "%lu", address->addr.in6.sin6_scope_id) > 0)
639 int LHNETADDRESS_GetPort(const lhnetaddress_t *address)
643 return address->port;
646 int LHNETADDRESS_SetPort(lhnetaddress_t *vaddress, int port)
648 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
651 address->port = port;
652 switch(address->addresstype)
654 case LHNETADDRESSTYPE_LOOP:
656 case LHNETADDRESSTYPE_INET4:
657 address->addr.in.sin_port = htons((unsigned short)port);
660 case LHNETADDRESSTYPE_INET6:
661 address->addr.in6.sin6_port = htons((unsigned short)port);
669 int LHNETADDRESS_Compare(const lhnetaddress_t *vaddress1, const lhnetaddress_t *vaddress2)
671 lhnetaddressnative_t *address1 = (lhnetaddressnative_t *)vaddress1;
672 lhnetaddressnative_t *address2 = (lhnetaddressnative_t *)vaddress2;
673 if (!address1 || !address2)
675 if (address1->addresstype != address2->addresstype)
677 switch(address1->addresstype)
679 case LHNETADDRESSTYPE_LOOP:
680 if (address1->port != address2->port)
683 case LHNETADDRESSTYPE_INET4:
684 if (address1->addr.in.sin_family != address2->addr.in.sin_family)
686 if (memcmp(&address1->addr.in.sin_addr, &address2->addr.in.sin_addr, sizeof(address1->addr.in.sin_addr)))
688 if (address1->port != address2->port)
692 case LHNETADDRESSTYPE_INET6:
693 if (address1->addr.in6.sin6_family != address2->addr.in6.sin6_family)
695 if (memcmp(&address1->addr.in6.sin6_addr, &address2->addr.in6.sin6_addr, sizeof(address1->addr.in6.sin6_addr)))
697 if (address1->port != address2->port)
706 typedef struct lhnetpacket_s
713 #ifndef STANDALONETEST
714 double sentdoubletime;
716 struct lhnetpacket_s *next, *prev;
720 static int lhnet_active;
721 static lhnetsocket_t lhnet_socketlist;
722 static lhnetpacket_t lhnet_packetlist;
724 static int lhnet_didWSAStartup = 0;
725 static WSADATA lhnet_winsockdata;
728 void LHNET_Init(void)
732 lhnet_socketlist.next = lhnet_socketlist.prev = &lhnet_socketlist;
733 lhnet_packetlist.next = lhnet_packetlist.prev = &lhnet_packetlist;
736 lhnet_didWSAStartup = !WSAStartup(MAKEWORD(1, 1), &lhnet_winsockdata);
737 if (!lhnet_didWSAStartup)
738 Con_Print("LHNET_Init: WSAStartup failed, networking disabled\n");
742 void LHNET_Shutdown(void)
747 while (lhnet_socketlist.next != &lhnet_socketlist)
748 LHNET_CloseSocket(lhnet_socketlist.next);
749 while (lhnet_packetlist.next != &lhnet_packetlist)
751 p = lhnet_packetlist.next;
752 p->prev->next = p->next;
753 p->next->prev = p->prev;
757 if (lhnet_didWSAStartup)
759 lhnet_didWSAStartup = 0;
766 static const char *LHNETPRIVATE_StrError(void)
769 int i = WSAGetLastError();
772 case WSAEINTR: return "WSAEINTR";
773 case WSAEBADF: return "WSAEBADF";
774 case WSAEACCES: return "WSAEACCES";
775 case WSAEFAULT: return "WSAEFAULT";
776 case WSAEINVAL: return "WSAEINVAL";
777 case WSAEMFILE: return "WSAEMFILE";
778 case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK";
779 case WSAEINPROGRESS: return "WSAEINPROGRESS";
780 case WSAEALREADY: return "WSAEALREADY";
781 case WSAENOTSOCK: return "WSAENOTSOCK";
782 case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ";
783 case WSAEMSGSIZE: return "WSAEMSGSIZE";
784 case WSAEPROTOTYPE: return "WSAEPROTOTYPE";
785 case WSAENOPROTOOPT: return "WSAENOPROTOOPT";
786 case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
787 case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
788 case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP";
789 case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT";
790 case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT";
791 case WSAEADDRINUSE: return "WSAEADDRINUSE";
792 case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL";
793 case WSAENETDOWN: return "WSAENETDOWN";
794 case WSAENETUNREACH: return "WSAENETUNREACH";
795 case WSAENETRESET: return "WSAENETRESET";
796 case WSAECONNABORTED: return "WSAECONNABORTED";
797 case WSAECONNRESET: return "WSAECONNRESET";
798 case WSAENOBUFS: return "WSAENOBUFS";
799 case WSAEISCONN: return "WSAEISCONN";
800 case WSAENOTCONN: return "WSAENOTCONN";
801 case WSAESHUTDOWN: return "WSAESHUTDOWN";
802 case WSAETOOMANYREFS: return "WSAETOOMANYREFS";
803 case WSAETIMEDOUT: return "WSAETIMEDOUT";
804 case WSAECONNREFUSED: return "WSAECONNREFUSED";
805 case WSAELOOP: return "WSAELOOP";
806 case WSAENAMETOOLONG: return "WSAENAMETOOLONG";
807 case WSAEHOSTDOWN: return "WSAEHOSTDOWN";
808 case WSAEHOSTUNREACH: return "WSAEHOSTUNREACH";
809 case WSAENOTEMPTY: return "WSAENOTEMPTY";
810 case WSAEPROCLIM: return "WSAEPROCLIM";
811 case WSAEUSERS: return "WSAEUSERS";
812 case WSAEDQUOT: return "WSAEDQUOT";
813 case WSAESTALE: return "WSAESTALE";
814 case WSAEREMOTE: return "WSAEREMOTE";
815 case WSAEDISCON: return "WSAEDISCON";
816 case 0: return "no error";
817 default: return "unknown WSAE error";
820 return strerror(errno);
824 void LHNET_SleepUntilPacket_Microseconds(int microseconds)
833 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
835 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
837 if (lastfd < s->inetsocket)
838 lastfd = s->inetsocket;
839 FD_SET((unsigned int)s->inetsocket, &fdreadset);
842 tv.tv_sec = microseconds / 1000000;
843 tv.tv_usec = microseconds % 1000000;
844 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
846 Sys_Sleep(microseconds);
850 lhnetsocket_t *LHNET_OpenSocket_Connectionless(lhnetaddress_t *address)
852 lhnetsocket_t *lhnetsocket, *s;
855 lhnetsocket = (lhnetsocket_t *)Z_Malloc(sizeof(*lhnetsocket));
858 memset(lhnetsocket, 0, sizeof(*lhnetsocket));
859 lhnetsocket->address = *address;
860 switch(lhnetsocket->address.addresstype)
862 case LHNETADDRESSTYPE_LOOP:
863 if (lhnetsocket->address.port == 0)
865 // allocate a port dynamically
866 // this search will always terminate because there is never
867 // an allocated socket with port 0, so if the number wraps it
868 // will find the port is unused, and then refuse to use port
869 // 0, causing an intentional failure condition
870 lhnetsocket->address.port = 1024;
873 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
874 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
876 if (s == &lhnet_socketlist)
878 lhnetsocket->address.port++;
881 // check if the port is available
882 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
883 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
885 if (s == &lhnet_socketlist && lhnetsocket->address.port != 0)
887 lhnetsocket->next = &lhnet_socketlist;
888 lhnetsocket->prev = lhnetsocket->next->prev;
889 lhnetsocket->next->prev = lhnetsocket;
890 lhnetsocket->prev->next = lhnetsocket;
894 case LHNETADDRESSTYPE_INET4:
896 case LHNETADDRESSTYPE_INET6:
899 if (lhnet_didWSAStartup)
903 if ((lhnetsocket->inetsocket = socket(address->addresstype == LHNETADDRESSTYPE_INET6 ? PF_INET6 : PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1)
905 if ((lhnetsocket->inetsocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1)
919 if (ioctlsocket(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
923 // We need to set this flag to tell the OS that we only listen on IPv6. If we don't
924 // most OSes will create a dual-protocol socket that also listens on IPv4. In this case
925 // if an IPv4 socket is already bound to the port we want, our bind() call will fail.
927 if (address->addresstype != LHNETADDRESSTYPE_INET6
928 || setsockopt (lhnetsocket->inetsocket, IPPROTO_IPV6, IPV6_V6ONLY,
929 (const char *)&ipv6_only, sizeof(ipv6_only)) == 0
931 // The Win32 API only supports IPV6_V6ONLY since Windows Vista, but fortunately
932 // the default value is what we want on Win32 anyway (IPV6_V6ONLY = true)
933 || SOCKETERRNO == WSAENOPROTOOPT
938 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
942 if (address->addresstype == LHNETADDRESSTYPE_INET6)
944 namelen = sizeof(localaddress->addr.in6);
945 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
946 if (bindresult != -1)
947 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
952 namelen = sizeof(localaddress->addr.in);
953 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
954 if (bindresult != -1)
955 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
957 if (bindresult != -1)
960 // enable broadcast on this socket
961 setsockopt(lhnetsocket->inetsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i));
962 lhnetsocket->next = &lhnet_socketlist;
963 lhnetsocket->prev = lhnetsocket->next->prev;
964 lhnetsocket->next->prev = lhnetsocket;
965 lhnetsocket->prev->next = lhnetsocket;
967 if (ioctlsocket(lhnetsocket->inetsocket, SIO_UDP_CONNRESET, &_false) == -1)
968 Con_DPrintf("LHNET_OpenSocket_Connectionless: ioctlsocket SIO_UDP_CONNRESET returned error: %s\n", LHNETPRIVATE_StrError());
973 Con_Printf("LHNET_OpenSocket_Connectionless: bind returned error: %s\n", LHNETPRIVATE_StrError());
977 Con_Printf("LHNET_OpenSocket_Connectionless: setsockopt(IPV6_V6ONLY) returned error: %s\n", LHNETPRIVATE_StrError());
981 Con_Printf("LHNET_OpenSocket_Connectionless: ioctlsocket returned error: %s\n", LHNETPRIVATE_StrError());
982 closesocket(lhnetsocket->inetsocket);
985 Con_Printf("LHNET_OpenSocket_Connectionless: socket returned error: %s\n", LHNETPRIVATE_StrError());
989 Con_Print("LHNET_OpenSocket_Connectionless: can't open a socket (WSAStartup failed during LHNET_Init)\n");
1000 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
1004 // unlink from socket list
1005 if (lhnetsocket->next == NULL)
1007 lhnetsocket->next->prev = lhnetsocket->prev;
1008 lhnetsocket->prev->next = lhnetsocket->next;
1009 lhnetsocket->next = NULL;
1010 lhnetsocket->prev = NULL;
1012 // no special close code for loopback, just inet
1013 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1015 closesocket(lhnetsocket->inetsocket);
1017 Z_Free(lhnetsocket);
1021 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
1024 return &sock->address;
1029 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *vaddress)
1031 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
1033 if (!lhnetsocket || !address || !content || maxcontentlength < 1)
1035 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
1038 lhnetpacket_t *p, *pnext;
1039 // scan for any old packets to timeout while searching for a packet
1040 // that is waiting to be delivered to this socket
1041 currenttime = time(NULL);
1042 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
1045 if (p->timeout < currenttime)
1048 p->next->prev = p->prev;
1049 p->prev->next = p->next;
1053 #ifndef STANDALONETEST
1054 if (cl_netlocalping.value && (realtime - cl_netlocalping.value * (1.0 / 2000.0)) < p->sentdoubletime)
1057 if (value == 0 && p->destinationport == lhnetsocket->address.port)
1059 if (p->length <= maxcontentlength)
1061 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
1062 *address = *localaddress;
1063 address->port = p->sourceport;
1064 memcpy(content, p->data, p->length);
1070 p->next->prev = p->prev;
1071 p->prev->next = p->next;
1076 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
1078 SOCKLEN_T inetaddresslength;
1079 address->addresstype = LHNETADDRESSTYPE_NONE;
1080 inetaddresslength = sizeof(address->addr.in);
1081 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, LHNET_RECVFROM_FLAGS, &address->addr.sock, &inetaddresslength);
1084 address->addresstype = LHNETADDRESSTYPE_INET4;
1085 address->port = ntohs(address->addr.in.sin_port);
1090 int e = SOCKETERRNO;
1091 if (e == EWOULDBLOCK)
1096 Con_Print("Connection refused\n");
1099 Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
1103 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1105 SOCKLEN_T inetaddresslength;
1106 address->addresstype = LHNETADDRESSTYPE_NONE;
1107 inetaddresslength = sizeof(address->addr.in6);
1108 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, 0, &address->addr.sock, &inetaddresslength);
1111 address->addresstype = LHNETADDRESSTYPE_INET6;
1112 address->port = ntohs(address->addr.in6.sin6_port);
1115 else if (value == -1)
1117 int e = SOCKETERRNO;
1118 if (e == EWOULDBLOCK)
1123 Con_Print("Connection refused\n");
1126 Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
1133 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *vaddress)
1135 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
1137 if (!lhnetsocket || !address || !content || contentlength < 1)
1139 if (lhnetsocket->address.addresstype != address->addresstype)
1141 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
1144 p = (lhnetpacket_t *)Z_Malloc(sizeof(*p) + contentlength);
1145 p->data = (void *)(p + 1);
1146 memcpy(p->data, content, contentlength);
1147 p->length = contentlength;
1148 p->sourceport = lhnetsocket->address.port;
1149 p->destinationport = address->port;
1150 p->timeout = time(NULL) + 10;
1151 p->next = &lhnet_packetlist;
1152 p->prev = p->next->prev;
1155 #ifndef STANDALONETEST
1156 p->sentdoubletime = realtime;
1158 value = contentlength;
1160 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
1162 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, LHNET_SENDTO_FLAGS, (struct sockaddr *)&address->addr.in, sizeof(struct sockaddr_in));
1165 if (SOCKETERRNO == EWOULDBLOCK)
1167 Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
1171 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
1173 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, 0, (struct sockaddr *)&address->addr.in6, sizeof(struct sockaddr_in6));
1176 if (SOCKETERRNO == EWOULDBLOCK)
1178 Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
1185 #ifdef STANDALONETEST
1186 int main(int argc, char **argv)
1189 char *buffer = "test", buffer2[1024];
1190 int blen = strlen(buffer);
1192 lhnetsocket_t *sock1;
1193 lhnetsocket_t *sock2;
1194 lhnetaddress_t myaddy1;
1195 lhnetaddress_t myaddy2;
1196 lhnetaddress_t myaddy3;
1197 lhnetaddress_t localhostaddy1;
1198 lhnetaddress_t localhostaddy2;
1202 printf("calling LHNET_Init\n");
1205 printf("calling LHNET_FromPort twice to create two local addresses\n");
1206 LHNETADDRESS_FromPort(&myaddy1, LHNETADDRESSTYPE_INET4, 4000);
1207 LHNETADDRESS_FromPort(&myaddy2, LHNETADDRESSTYPE_INET4, 4001);
1208 LHNETADDRESS_FromString(&localhostaddy1, "127.0.0.1", 4000);
1209 LHNETADDRESS_FromString(&localhostaddy2, "127.0.0.1", 4001);
1211 printf("calling LHNET_OpenSocket_Connectionless twice to create two local sockets\n");
1212 sock1 = LHNET_OpenSocket_Connectionless(&myaddy1);
1213 sock2 = LHNET_OpenSocket_Connectionless(&myaddy2);
1215 printf("calling LHNET_Write to send a packet from the first socket to the second socket\n");
1216 test1 = LHNET_Write(sock1, buffer, blen, &localhostaddy2);
1217 printf("sleeping briefly\n");
1223 printf("calling LHNET_Read on the second socket to read the packet sent from the first socket\n");
1224 test2 = LHNET_Read(sock2, buffer2, b2len - 1, &myaddy3);
1226 Con_Printf("socket to socket test succeeded\n");
1228 Con_Printf("socket to socket test failed\n");
1231 printf("press any key to exit\n");
1235 printf("calling LHNET_Shutdown\n");
1237 printf("exiting\n");
1240 lhnetsocket_t *sock[16], *sendsock;
1249 int sendmessagelength;
1250 lhnetaddress_t destaddress;
1251 lhnetaddress_t receiveaddress;
1252 lhnetaddress_t sockaddress[16];
1253 char buffer[1536], addressstring[128], addressstring2[128];
1254 if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
1256 printf("calling LHNET_Init()\n");
1260 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
1261 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
1262 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
1266 sendmessagelength = 0;
1268 for (i = 0;i < numsockets;i++)
1270 LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
1271 printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
1272 if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
1274 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1275 printf("opened socket successfully (address \"%s\")\n", addressstring2);
1279 printf("failed to open socket\n");
1290 count = atoi(argv[2]);
1291 if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
1293 sendmessage = argv[4];
1294 sendmessagelength = strlen(sendmessage);
1296 for (i = 0;i < numsockets;i++)
1297 if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
1299 if (sendsock == NULL)
1301 printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
1307 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
1311 printf("started, now listening for \"exit\" on the opened sockets\n");
1312 oldtime = time(NULL);
1320 for (i = 0;i < numsockets;i++)
1324 length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
1326 printf("localsock read error: length < 0");
1327 else if (length > 0 && length < (int)sizeof(buffer))
1330 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
1331 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1332 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
1333 if (!strcmp(buffer, "exit"))
1340 if (argc == 5 && count > 0)
1342 newtime = time(NULL);
1343 if (newtime != oldtime)
1345 LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
1346 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
1347 printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
1348 length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
1349 if (length == sendmessagelength)
1350 printf("sent successfully\n");
1352 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
1356 printf("Done sending, still listening for \"exit\"\n");
1360 for (i = 0;i < numsockets;i++)
1364 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1365 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
1366 LHNET_CloseSocket(sock[i]);
1369 printf("calling LHNET_Shutdown()\n");
1373 printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");