2 // Written by Forest Hale 2003-06-15 and placed into public domain.
5 // Windows XP or higher is required for getaddrinfo, but the inclusion of wspiapi provides fallbacks for older versions
6 # define _WIN32_WINNT 0x0501
11 # include <ws2tcpip.h>
15 #ifndef STANDALONETEST
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/ioctl.h>
30 #include <netinet/in.h>
31 #include <arpa/inet.h>
36 #include <proto/socket.h>
39 // for Z_Malloc/Z_Free in quake
40 #ifndef STANDALONETEST
45 #define Con_Print printf
46 #define Con_Printf printf
47 #define Z_Malloc malloc
54 #define EWOULDBLOCK WSAEWOULDBLOCK
55 #define ECONNREFUSED WSAECONNREFUSED
57 #define SOCKETERRNO WSAGetLastError()
59 #define IOC_VENDOR 0x18000000
60 #define _WSAIOW(x,y) (IOC_IN|(x)|(y))
61 #define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
64 #elif defined(__MORPHOS__)
65 #define ioctlsocket IoctlSocket
66 #define closesocket CloseSocket
67 #define SOCKETERRNO Errno()
71 #define ioctlsocket ioctl
72 #define closesocket close
73 #define SOCKETERRNO errno
75 #define SOCKLEN_T socklen_t
78 typedef struct lhnetaddressnative_s
80 lhnetaddresstype_t addresstype;
85 struct sockaddr_in in;
86 struct sockaddr_in6 in6;
92 // to make LHNETADDRESS_FromString resolve repeated hostnames faster, cache them
93 #define MAX_NAMECACHE 64
94 static struct namecache_s
96 lhnetaddressnative_t address;
97 double expirationtime;
100 namecache[MAX_NAMECACHE];
101 static int namecacheposition = 0;
103 int LHNETADDRESS_FromPort(lhnetaddress_t *vaddress, lhnetaddresstype_t addresstype, int port)
105 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
112 case LHNETADDRESSTYPE_LOOP:
113 // local:port (loopback)
114 memset(address, 0, sizeof(*address));
115 address->addresstype = LHNETADDRESSTYPE_LOOP;
116 address->port = port;
118 case LHNETADDRESSTYPE_INET4:
119 // 0.0.0.0:port (INADDR_ANY, binds to all interfaces)
120 memset(address, 0, sizeof(*address));
121 address->addresstype = LHNETADDRESSTYPE_INET4;
122 address->port = port;
123 address->addr.in.sin_family = AF_INET;
124 address->addr.in.sin_port = htons((unsigned short)port);
126 case LHNETADDRESSTYPE_INET6:
127 // [0:0:0:0:0:0:0:0]:port (IN6ADDR_ANY, binds to all interfaces)
128 memset(address, 0, sizeof(*address));
129 address->addresstype = LHNETADDRESSTYPE_INET6;
130 address->port = port;
131 address->addr.in6.sin6_family = AF_INET6;
132 address->addr.in6.sin6_port = htons((unsigned short)port);
138 int LHNETADDRESS_Resolve(lhnetaddressnative_t *address, const char *name, int port)
141 struct addrinfo hints;
142 struct addrinfo* addrinf;
145 dpsnprintf (port_buff, sizeof (port_buff), "%d", port);
146 port_buff[sizeof (port_buff) - 1] = '\0';
148 memset(&hints, 0, sizeof (hints));
149 hints.ai_family = AF_UNSPEC;
150 hints.ai_socktype = SOCK_DGRAM;
151 //hints.ai_flags = AI_PASSIVE;
153 err = getaddrinfo(name, port_buff, &hints, &addrinf);
154 if (err != 0 || addrinf == NULL)
156 if (addrinf->ai_addr->sa_family != AF_INET6 && addrinf->ai_addr->sa_family != AF_INET)
158 freeaddrinfo (addrinf);
163 if (addrinf->ai_addr->sa_family == AF_INET6)
165 address->addresstype = LHNETADDRESSTYPE_INET6;
166 memcpy(&address->addr.in6, addrinf->ai_addr, sizeof(address->addr.in6));
170 address->addresstype = LHNETADDRESSTYPE_INET4;
171 memcpy(&address->addr.in, addrinf->ai_addr, sizeof(address->addr.in));
173 address->port = port;
175 freeaddrinfo (addrinf);
179 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
181 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
182 int i, port, d1, d2, d3, d4, resolved;
186 #ifdef STANDALONETEST
189 const char* addr_start;
190 const char* addr_end = NULL;
191 const char* port_name = NULL;
192 int addr_family = AF_UNSPEC;
194 if (!address || !string || !*string)
196 memset(address, 0, sizeof(*address));
197 address->addresstype = LHNETADDRESSTYPE_NONE;
200 // If it's a bracketed IPv6 address
201 if (string[0] == '[')
203 const char* end_bracket = strchr(string, ']');
205 if (end_bracket == NULL)
208 if (end_bracket[1] == ':')
209 port_name = end_bracket + 2;
210 else if (end_bracket[1] != '\0')
213 addr_family = AF_INET6;
214 addr_start = &string[1];
215 addr_end = end_bracket;
219 const char* first_colon;
223 // If it's a numeric non-bracket IPv6 address (-> no port),
224 // or it's a numeric IPv4 address, or a name, with a port
225 first_colon = strchr(string, ':');
226 if (first_colon != NULL)
228 const char* last_colon = strrchr(first_colon + 1, ':');
230 // If it's an numeric IPv4 address, or a name, with a port
231 if (last_colon == NULL)
233 addr_end = first_colon;
234 port_name = first_colon + 1;
237 addr_family = AF_INET6;
241 if (addr_end != NULL)
242 namelen = addr_end - addr_start;
244 namelen = strlen (addr_start);
246 if (namelen >= sizeof(name))
247 namelen = sizeof(name) - 1;
248 memcpy (name, addr_start, namelen);
252 port = atoi(port_name);
258 if (!strcmp(name, "local"))
260 address->addresstype = LHNETADDRESSTYPE_LOOP;
261 address->port = port;
264 // try to parse as dotted decimal ipv4 address first
265 // note this supports partial ip addresses
266 d1 = d2 = d3 = d4 = 0;
268 #define sscanf sscanf_s
270 if (addr_family != AF_INET6 &&
271 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)
273 // parsed a valid ipv4 address
274 address->addresstype = LHNETADDRESSTYPE_INET4;
275 address->port = port;
276 address->addr.in.sin_family = AF_INET;
277 address->addr.in.sin_port = htons((unsigned short)port);
278 a = (unsigned char *)&address->addr.in.sin_addr;
283 #ifdef STANDALONETEST
284 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
285 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %s\n", string, string2);
289 for (i = 0;i < MAX_NAMECACHE;i++)
290 if (!strcmp(namecache[i].name, name))
292 #ifdef STANDALONETEST
293 if (i < MAX_NAMECACHE)
295 if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
298 *address = namecache[i].address;
299 address->port = port;
300 if (address->addresstype == LHNETADDRESSTYPE_INET6)
302 address->addr.in6.sin6_port = htons((unsigned short)port);
305 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
307 address->addr.in.sin_port = htons((unsigned short)port);
313 for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
314 namecache[namecacheposition].name[i] = name[i];
315 namecache[namecacheposition].name[i] = 0;
316 #ifndef STANDALONETEST
317 namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
320 // try resolving the address (handles dns and other ip formats)
321 resolved = LHNETADDRESS_Resolve(address, name, port);
324 #ifdef STANDALONETEST
325 const char *protoname;
327 switch (address->addresstype)
329 case LHNETADDRESSTYPE_INET6:
332 case LHNETADDRESSTYPE_INET4:
336 protoname = "UNKNOWN";
339 LHNETADDRESS_ToString(vaddress, string2, sizeof(string2), 1);
340 Con_Printf("LHNETADDRESS_Resolve(\"%s\") returned %s address %s\n", string, protoname, string2);
342 namecache[namecacheposition].address = *address;
346 #ifdef STANDALONETEST
347 printf("name resolution failed on address \"%s\"\n", name);
349 namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
352 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
356 int LHNETADDRESS_ToString(const lhnetaddress_t *vaddress, char *string, int stringbuffersize, int includeport)
358 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
359 const unsigned char *a;
361 if (!address || !string || stringbuffersize < 1)
363 switch(address->addresstype)
367 case LHNETADDRESSTYPE_LOOP:
370 if (stringbuffersize >= 12)
372 dpsnprintf(string, stringbuffersize, "local:%d", address->port);
378 if (stringbuffersize >= 6)
380 memcpy(string, "local", 6);
385 case LHNETADDRESSTYPE_INET4:
386 a = (const unsigned char *)(&address->addr.in.sin_addr);
389 if (stringbuffersize >= 22)
391 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d:%d", a[0], a[1], a[2], a[3], address->port);
397 if (stringbuffersize >= 16)
399 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
404 case LHNETADDRESSTYPE_INET6:
405 a = (const unsigned char *)(&address->addr.in6.sin6_addr);
408 if (stringbuffersize >= 88)
410 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);
416 if (stringbuffersize >= 80)
418 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]);
427 int LHNETADDRESS_GetAddressType(const lhnetaddress_t *address)
430 return address->addresstype;
432 return LHNETADDRESSTYPE_NONE;
435 const char *LHNETADDRESS_GetInterfaceName(const lhnetaddress_t *vaddress)
437 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
439 if (address && address->addresstype == LHNETADDRESSTYPE_INET6)
443 static char ifname [IF_NAMESIZE];
445 if (if_indextoname(address->addr.in6.sin6_scope_id, ifname) == ifname)
450 // The Win32 API doesn't have if_indextoname() until Windows Vista,
451 // but luckily it just uses the interface ID as the interface name
453 static char ifname [16];
455 if (dpsnprintf(ifname, sizeof(ifname), "%lu", address->addr.in6.sin6_scope_id) > 0)
464 int LHNETADDRESS_GetPort(const lhnetaddress_t *address)
468 return address->port;
471 int LHNETADDRESS_SetPort(lhnetaddress_t *vaddress, int port)
473 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
476 address->port = port;
477 switch(address->addresstype)
479 case LHNETADDRESSTYPE_LOOP:
481 case LHNETADDRESSTYPE_INET4:
482 address->addr.in.sin_port = htons((unsigned short)port);
484 case LHNETADDRESSTYPE_INET6:
485 address->addr.in6.sin6_port = htons((unsigned short)port);
492 int LHNETADDRESS_Compare(const lhnetaddress_t *vaddress1, const lhnetaddress_t *vaddress2)
494 lhnetaddressnative_t *address1 = (lhnetaddressnative_t *)vaddress1;
495 lhnetaddressnative_t *address2 = (lhnetaddressnative_t *)vaddress2;
496 if (!address1 || !address2)
498 if (address1->addresstype != address2->addresstype)
500 switch(address1->addresstype)
502 case LHNETADDRESSTYPE_LOOP:
503 if (address1->port != address2->port)
506 case LHNETADDRESSTYPE_INET4:
507 if (address1->addr.in.sin_family != address2->addr.in.sin_family)
509 if (memcmp(&address1->addr.in.sin_addr, &address2->addr.in.sin_addr, sizeof(address1->addr.in.sin_addr)))
511 if (address1->port != address2->port)
514 case LHNETADDRESSTYPE_INET6:
515 if (address1->addr.in6.sin6_family != address2->addr.in6.sin6_family)
517 if (memcmp(&address1->addr.in6.sin6_addr, &address2->addr.in6.sin6_addr, sizeof(address1->addr.in6.sin6_addr)))
519 if (address1->port != address2->port)
527 typedef struct lhnetpacket_s
534 #ifndef STANDALONETEST
535 double sentdoubletime;
537 struct lhnetpacket_s *next, *prev;
541 static int lhnet_active;
542 static lhnetsocket_t lhnet_socketlist;
543 static lhnetpacket_t lhnet_packetlist;
545 static int lhnet_didWSAStartup = 0;
546 static WSADATA lhnet_winsockdata;
549 void LHNET_Init(void)
553 lhnet_socketlist.next = lhnet_socketlist.prev = &lhnet_socketlist;
554 lhnet_packetlist.next = lhnet_packetlist.prev = &lhnet_packetlist;
557 lhnet_didWSAStartup = !WSAStartup(MAKEWORD(1, 1), &lhnet_winsockdata);
558 if (!lhnet_didWSAStartup)
559 Con_Print("LHNET_Init: WSAStartup failed, networking disabled\n");
563 void LHNET_Shutdown(void)
568 while (lhnet_socketlist.next != &lhnet_socketlist)
569 LHNET_CloseSocket(lhnet_socketlist.next);
570 while (lhnet_packetlist.next != &lhnet_packetlist)
572 p = lhnet_packetlist.next;
573 p->prev->next = p->next;
574 p->next->prev = p->prev;
578 if (lhnet_didWSAStartup)
580 lhnet_didWSAStartup = 0;
587 static const char *LHNETPRIVATE_StrError(void)
590 int i = WSAGetLastError();
593 case WSAEINTR: return "WSAEINTR";
594 case WSAEBADF: return "WSAEBADF";
595 case WSAEACCES: return "WSAEACCES";
596 case WSAEFAULT: return "WSAEFAULT";
597 case WSAEINVAL: return "WSAEINVAL";
598 case WSAEMFILE: return "WSAEMFILE";
599 case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK";
600 case WSAEINPROGRESS: return "WSAEINPROGRESS";
601 case WSAEALREADY: return "WSAEALREADY";
602 case WSAENOTSOCK: return "WSAENOTSOCK";
603 case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ";
604 case WSAEMSGSIZE: return "WSAEMSGSIZE";
605 case WSAEPROTOTYPE: return "WSAEPROTOTYPE";
606 case WSAENOPROTOOPT: return "WSAENOPROTOOPT";
607 case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
608 case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
609 case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP";
610 case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT";
611 case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT";
612 case WSAEADDRINUSE: return "WSAEADDRINUSE";
613 case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL";
614 case WSAENETDOWN: return "WSAENETDOWN";
615 case WSAENETUNREACH: return "WSAENETUNREACH";
616 case WSAENETRESET: return "WSAENETRESET";
617 case WSAECONNABORTED: return "WSAECONNABORTED";
618 case WSAECONNRESET: return "WSAECONNRESET";
619 case WSAENOBUFS: return "WSAENOBUFS";
620 case WSAEISCONN: return "WSAEISCONN";
621 case WSAENOTCONN: return "WSAENOTCONN";
622 case WSAESHUTDOWN: return "WSAESHUTDOWN";
623 case WSAETOOMANYREFS: return "WSAETOOMANYREFS";
624 case WSAETIMEDOUT: return "WSAETIMEDOUT";
625 case WSAECONNREFUSED: return "WSAECONNREFUSED";
626 case WSAELOOP: return "WSAELOOP";
627 case WSAENAMETOOLONG: return "WSAENAMETOOLONG";
628 case WSAEHOSTDOWN: return "WSAEHOSTDOWN";
629 case WSAEHOSTUNREACH: return "WSAEHOSTUNREACH";
630 case WSAENOTEMPTY: return "WSAENOTEMPTY";
631 case WSAEPROCLIM: return "WSAEPROCLIM";
632 case WSAEUSERS: return "WSAEUSERS";
633 case WSAEDQUOT: return "WSAEDQUOT";
634 case WSAESTALE: return "WSAESTALE";
635 case WSAEREMOTE: return "WSAEREMOTE";
636 case WSAEDISCON: return "WSAEDISCON";
637 case 0: return "no error";
638 default: return "unknown WSAE error";
641 return strerror(errno);
645 void LHNET_SleepUntilPacket_Microseconds(int microseconds)
653 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
655 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
657 if (lastfd < s->inetsocket)
658 lastfd = s->inetsocket;
659 FD_SET((unsigned int)s->inetsocket, &fdreadset);
662 tv.tv_sec = microseconds / 1000000;
663 tv.tv_usec = microseconds % 1000000;
664 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
667 lhnetsocket_t *LHNET_OpenSocket_Connectionless(lhnetaddress_t *address)
669 lhnetsocket_t *lhnetsocket, *s;
672 lhnetsocket = (lhnetsocket_t *)Z_Malloc(sizeof(*lhnetsocket));
675 memset(lhnetsocket, 0, sizeof(*lhnetsocket));
676 lhnetsocket->address = *address;
677 switch(lhnetsocket->address.addresstype)
679 case LHNETADDRESSTYPE_LOOP:
680 if (lhnetsocket->address.port == 0)
682 // allocate a port dynamically
683 // this search will always terminate because there is never
684 // an allocated socket with port 0, so if the number wraps it
685 // will find the port is unused, and then refuse to use port
686 // 0, causing an intentional failure condition
687 lhnetsocket->address.port = 1024;
690 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
691 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
693 if (s == &lhnet_socketlist)
695 lhnetsocket->address.port++;
698 // check if the port is available
699 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
700 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
702 if (s == &lhnet_socketlist && lhnetsocket->address.port != 0)
704 lhnetsocket->next = &lhnet_socketlist;
705 lhnetsocket->prev = lhnetsocket->next->prev;
706 lhnetsocket->next->prev = lhnetsocket;
707 lhnetsocket->prev->next = lhnetsocket;
711 case LHNETADDRESSTYPE_INET4:
712 case LHNETADDRESSTYPE_INET6:
714 if (lhnet_didWSAStartup)
717 if ((lhnetsocket->inetsocket = socket(address->addresstype == LHNETADDRESSTYPE_INET6 ? PF_INET6 : PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1)
725 if (ioctlsocket(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
728 // We need to set this flag to tell the OS that we only listen on IPv6. If we don't
729 // most OSes will create a dual-protocol socket that also listens on IPv4. In this case
730 // if an IPv4 socket is already bound to the port we want, our bind() call will fail.
732 if (address->addresstype != LHNETADDRESSTYPE_INET6
733 || setsockopt (lhnetsocket->inetsocket, IPPROTO_IPV6, IPV6_V6ONLY,
734 (const char *)&ipv6_only, sizeof(ipv6_only)) == 0
736 // The Win32 API only supports IPV6_V6ONLY since Windows Vista, but fortunately
737 // the default value is what we want on Win32 anyway (IPV6_V6ONLY = true)
738 || SOCKETERRNO == WSAENOPROTOOPT
743 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
746 if (address->addresstype == LHNETADDRESSTYPE_INET6)
748 namelen = sizeof(localaddress->addr.in6);
749 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
750 if (bindresult != -1)
751 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
755 namelen = sizeof(localaddress->addr.in);
756 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
757 if (bindresult != -1)
758 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
760 if (bindresult != -1)
763 // enable broadcast on this socket
764 setsockopt(lhnetsocket->inetsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i));
765 lhnetsocket->next = &lhnet_socketlist;
766 lhnetsocket->prev = lhnetsocket->next->prev;
767 lhnetsocket->next->prev = lhnetsocket;
768 lhnetsocket->prev->next = lhnetsocket;
770 if (ioctlsocket(lhnetsocket->inetsocket, SIO_UDP_CONNRESET, &_false) == -1)
771 Con_DPrintf("LHNET_OpenSocket_Connectionless: ioctlsocket SIO_UDP_CONNRESET returned error: %s\n", LHNETPRIVATE_StrError());
776 Con_Printf("LHNET_OpenSocket_Connectionless: bind returned error: %s\n", LHNETPRIVATE_StrError());
780 Con_Printf("LHNET_OpenSocket_Connectionless: setsockopt(IPV6_V6ONLY) returned error: %s\n", LHNETPRIVATE_StrError());
784 Con_Printf("LHNET_OpenSocket_Connectionless: ioctlsocket returned error: %s\n", LHNETPRIVATE_StrError());
785 closesocket(lhnetsocket->inetsocket);
788 Con_Printf("LHNET_OpenSocket_Connectionless: socket returned error: %s\n", LHNETPRIVATE_StrError());
792 Con_Print("LHNET_OpenSocket_Connectionless: can't open a socket (WSAStartup failed during LHNET_Init)\n");
803 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
807 // unlink from socket list
808 if (lhnetsocket->next == NULL)
810 lhnetsocket->next->prev = lhnetsocket->prev;
811 lhnetsocket->prev->next = lhnetsocket->next;
812 lhnetsocket->next = NULL;
813 lhnetsocket->prev = NULL;
815 // no special close code for loopback, just inet
816 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
818 closesocket(lhnetsocket->inetsocket);
824 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
827 return &sock->address;
832 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *vaddress)
834 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
836 if (!lhnetsocket || !address || !content || maxcontentlength < 1)
838 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
841 lhnetpacket_t *p, *pnext;
842 // scan for any old packets to timeout while searching for a packet
843 // that is waiting to be delivered to this socket
844 currenttime = time(NULL);
845 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
848 if (p->timeout < currenttime)
851 p->next->prev = p->prev;
852 p->prev->next = p->next;
856 #ifndef STANDALONETEST
857 if (cl_netlocalping.value && (realtime - cl_netlocalping.value * (1.0 / 2000.0)) < p->sentdoubletime)
860 if (value == 0 && p->destinationport == lhnetsocket->address.port)
862 if (p->length <= maxcontentlength)
864 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
865 *address = *localaddress;
866 address->port = p->sourceport;
867 memcpy(content, p->data, p->length);
873 p->next->prev = p->prev;
874 p->prev->next = p->next;
879 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
881 SOCKLEN_T inetaddresslength;
882 address->addresstype = LHNETADDRESSTYPE_NONE;
883 inetaddresslength = sizeof(address->addr.in);
884 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, 0, &address->addr.sock, &inetaddresslength);
887 address->addresstype = LHNETADDRESSTYPE_INET4;
888 address->port = ntohs(address->addr.in.sin_port);
891 else if (value == -1)
894 if (e == EWOULDBLOCK)
899 Con_Print("Connection refused\n");
902 Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
905 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
907 SOCKLEN_T inetaddresslength;
908 address->addresstype = LHNETADDRESSTYPE_NONE;
909 inetaddresslength = sizeof(address->addr.in6);
910 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, 0, &address->addr.sock, &inetaddresslength);
913 address->addresstype = LHNETADDRESSTYPE_INET6;
914 address->port = ntohs(address->addr.in6.sin6_port);
917 else if (value == -1)
920 if (e == EWOULDBLOCK)
925 Con_Print("Connection refused\n");
928 Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
934 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *vaddress)
936 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
938 if (!lhnetsocket || !address || !content || contentlength < 1)
940 if (lhnetsocket->address.addresstype != address->addresstype)
942 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
945 p = (lhnetpacket_t *)Z_Malloc(sizeof(*p) + contentlength);
946 p->data = (void *)(p + 1);
947 memcpy(p->data, content, contentlength);
948 p->length = contentlength;
949 p->sourceport = lhnetsocket->address.port;
950 p->destinationport = address->port;
951 p->timeout = time(NULL) + 10;
952 p->next = &lhnet_packetlist;
953 p->prev = p->next->prev;
956 #ifndef STANDALONETEST
957 p->sentdoubletime = realtime;
959 value = contentlength;
961 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
963 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, 0, (struct sockaddr *)&address->addr.in, sizeof(struct sockaddr_in));
966 if (SOCKETERRNO == EWOULDBLOCK)
968 Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
971 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
973 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, 0, (struct sockaddr *)&address->addr.in6, sizeof(struct sockaddr_in6));
976 if (SOCKETERRNO == EWOULDBLOCK)
978 Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
984 #ifdef STANDALONETEST
985 int main(int argc, char **argv)
988 char *buffer = "test", buffer2[1024];
989 int blen = strlen(buffer);
991 lhnetsocket_t *sock1;
992 lhnetsocket_t *sock2;
993 lhnetaddress_t myaddy1;
994 lhnetaddress_t myaddy2;
995 lhnetaddress_t myaddy3;
996 lhnetaddress_t localhostaddy1;
997 lhnetaddress_t localhostaddy2;
1001 printf("calling LHNET_Init\n");
1004 printf("calling LHNET_FromPort twice to create two local addresses\n");
1005 LHNETADDRESS_FromPort(&myaddy1, LHNETADDRESSTYPE_INET4, 4000);
1006 LHNETADDRESS_FromPort(&myaddy2, LHNETADDRESSTYPE_INET4, 4001);
1007 LHNETADDRESS_FromString(&localhostaddy1, "127.0.0.1", 4000);
1008 LHNETADDRESS_FromString(&localhostaddy2, "127.0.0.1", 4001);
1010 printf("calling LHNET_OpenSocket_Connectionless twice to create two local sockets\n");
1011 sock1 = LHNET_OpenSocket_Connectionless(&myaddy1);
1012 sock2 = LHNET_OpenSocket_Connectionless(&myaddy2);
1014 printf("calling LHNET_Write to send a packet from the first socket to the second socket\n");
1015 test1 = LHNET_Write(sock1, buffer, blen, &localhostaddy2);
1016 printf("sleeping briefly\n");
1022 printf("calling LHNET_Read on the second socket to read the packet sent from the first socket\n");
1023 test2 = LHNET_Read(sock2, buffer2, b2len - 1, &myaddy3);
1025 Con_Printf("socket to socket test succeeded\n");
1027 Con_Printf("socket to socket test failed\n");
1030 printf("press any key to exit\n");
1034 printf("calling LHNET_Shutdown\n");
1036 printf("exiting\n");
1039 lhnetsocket_t *sock[16], *sendsock;
1048 int sendmessagelength;
1049 lhnetaddress_t destaddress;
1050 lhnetaddress_t receiveaddress;
1051 lhnetaddress_t sockaddress[16];
1052 char buffer[1536], addressstring[128], addressstring2[128];
1053 if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
1055 printf("calling LHNET_Init()\n");
1059 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
1060 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
1061 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
1065 sendmessagelength = 0;
1067 for (i = 0;i < numsockets;i++)
1069 LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
1070 printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
1071 if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
1073 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1074 printf("opened socket successfully (address \"%s\")\n", addressstring2);
1078 printf("failed to open socket\n");
1089 count = atoi(argv[2]);
1090 if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
1092 sendmessage = argv[4];
1093 sendmessagelength = strlen(sendmessage);
1095 for (i = 0;i < numsockets;i++)
1096 if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
1098 if (sendsock == NULL)
1100 printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
1106 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
1110 printf("started, now listening for \"exit\" on the opened sockets\n");
1111 oldtime = time(NULL);
1119 for (i = 0;i < numsockets;i++)
1123 length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
1125 printf("localsock read error: length < 0");
1126 else if (length > 0 && length < (int)sizeof(buffer))
1129 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
1130 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1131 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
1132 if (!strcmp(buffer, "exit"))
1139 if (argc == 5 && count > 0)
1141 newtime = time(NULL);
1142 if (newtime != oldtime)
1144 LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
1145 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
1146 printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
1147 length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
1148 if (length == sendmessagelength)
1149 printf("sent successfully\n");
1151 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
1155 printf("Done sending, still listening for \"exit\"\n");
1159 for (i = 0;i < numsockets;i++)
1163 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1164 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
1165 LHNET_CloseSocket(sock[i]);
1168 printf("calling LHNET_Shutdown()\n");
1172 printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");