2 // Written by Forest Hale 2003-06-15 and placed into public domain.
13 #define _WIN32_WINNT 0x0501
14 // Windows XP or higher is required for getaddrinfo
19 #include <sys/types.h>
20 #include <sys/socket.h>
21 #include <sys/ioctl.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
30 #include <proto/socket.h>
33 // for Z_Malloc/Z_Free in quake
34 #ifndef STANDALONETEST
39 #define Con_Print printf
40 #define Con_Printf printf
41 #define Z_Malloc malloc
48 #define EWOULDBLOCK WSAEWOULDBLOCK
49 #define ECONNREFUSED WSAECONNREFUSED
51 #define SOCKETERRNO WSAGetLastError()
53 #define IOC_VENDOR 0x18000000
54 #define _WSAIOW(x,y) (IOC_IN|(x)|(y))
55 #define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
58 #elif defined(__MORPHOS__)
59 #define ioctlsocket IoctlSocket
60 #define closesocket CloseSocket
61 #define SOCKETERRNO Errno()
65 #define ioctlsocket ioctl
66 #define closesocket close
67 #define SOCKETERRNO errno
69 #define SOCKLEN_T socklen_t
72 typedef struct lhnetaddressnative_s
74 lhnetaddresstype_t addresstype;
79 struct sockaddr_in in;
80 struct sockaddr_in6 in6;
86 // to make LHNETADDRESS_FromString resolve repeated hostnames faster, cache them
87 #define MAX_NAMECACHE 64
88 static struct namecache_s
90 lhnetaddressnative_t address;
91 double expirationtime;
94 namecache[MAX_NAMECACHE];
95 static int namecacheposition = 0;
97 int LHNETADDRESS_FromPort(lhnetaddress_t *vaddress, lhnetaddresstype_t addresstype, int port)
99 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
106 case LHNETADDRESSTYPE_LOOP:
107 // local:port (loopback)
108 memset(address, 0, sizeof(*address));
109 address->addresstype = LHNETADDRESSTYPE_LOOP;
110 address->port = port;
112 case LHNETADDRESSTYPE_INET4:
113 // 0.0.0.0:port (INADDR_ANY, binds to all interfaces)
114 memset(address, 0, sizeof(*address));
115 address->addresstype = LHNETADDRESSTYPE_INET4;
116 address->port = port;
117 address->addr.in.sin_family = AF_INET;
118 address->addr.in.sin_port = htons((unsigned short)port);
120 case LHNETADDRESSTYPE_INET6:
121 // [0:0:0:0:0:0:0:0]:port (IN6ADDR_ANY, binds to all interfaces)
122 memset(address, 0, sizeof(*address));
123 address->addresstype = LHNETADDRESSTYPE_INET6;
124 address->port = port;
125 address->addr.in6.sin6_family = AF_INET6;
126 address->addr.in6.sin6_port = htons((unsigned short)port);
132 int LHNETADDRESS_Resolve(lhnetaddressnative_t *address, const char *name, int port)
135 struct addrinfo hints;
136 struct addrinfo* addrinf;
139 dpsnprintf (port_buff, sizeof (port_buff), "%d", port);
140 port_buff[sizeof (port_buff) - 1] = '\0';
142 memset(&hints, 0, sizeof (hints));
143 hints.ai_family = AF_UNSPEC;
144 hints.ai_socktype = SOCK_DGRAM;
145 //hints.ai_flags = AI_PASSIVE;
147 err = getaddrinfo(name, port_buff, &hints, &addrinf);
148 if (err != 0 || addrinf == NULL)
150 if (addrinf->ai_addr->sa_family != AF_INET6 && addrinf->ai_addr->sa_family != AF_INET)
154 if (addrinf->ai_addr->sa_family == AF_INET6)
156 address->addresstype = LHNETADDRESSTYPE_INET6;
157 memcpy(&address->addr.in6, addrinf->ai_addr, sizeof(address->addr.in6));
161 address->addresstype = LHNETADDRESSTYPE_INET4;
162 memcpy(&address->addr.in, addrinf->ai_addr, sizeof(address->addr.in));
164 address->port = port;
166 freeaddrinfo (addrinf);
170 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
172 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
173 int i, port, d1, d2, d3, d4, resolved;
177 #ifdef STANDALONETEST
180 const char* addr_start;
181 const char* addr_end = NULL;
182 const char* port_name = NULL;
183 int addr_family = AF_UNSPEC;
185 if (!address || !string || !*string)
187 memset(address, 0, sizeof(*address));
188 address->addresstype = LHNETADDRESSTYPE_NONE;
191 // If it's a bracketed IPv6 address
192 if (string[0] == '[')
194 const char* end_bracket = strchr(string, ']');
196 if (end_bracket == NULL)
199 if (end_bracket[1] == ':')
200 port_name = end_bracket + 2;
201 else if (end_bracket[1] != '\0')
204 addr_family = AF_INET6;
205 addr_start = &string[1];
206 addr_end = end_bracket;
210 const char* first_colon;
214 // If it's a numeric non-bracket IPv6 address (-> no port),
215 // or it's a numeric IPv4 address, or a name, with a port
216 first_colon = strchr(string, ':');
217 if (first_colon != NULL)
219 const char* last_colon = strrchr(first_colon + 1, ':');
221 // If it's an numeric IPv4 address, or a name, with a port
222 if (last_colon == NULL)
224 addr_end = first_colon;
225 port_name = first_colon + 1;
228 addr_family = AF_INET6;
232 if (addr_end != NULL)
233 namelen = addr_end - addr_start;
235 namelen = strlen (addr_start);
237 if (namelen >= sizeof(name))
238 namelen = sizeof(name) - 1;
239 memcpy (name, addr_start, namelen);
243 port = atoi(port_name);
249 if (!strcmp(name, "local"))
251 address->addresstype = LHNETADDRESSTYPE_LOOP;
252 address->port = port;
255 // try to parse as dotted decimal ipv4 address first
256 // note this supports partial ip addresses
257 d1 = d2 = d3 = d4 = 0;
259 #define sscanf sscanf_s
261 if (addr_family != AF_INET6 &&
262 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)
264 // parsed a valid ipv4 address
265 address->addresstype = LHNETADDRESSTYPE_INET4;
266 address->port = port;
267 address->addr.in.sin_family = AF_INET;
268 address->addr.in.sin_port = htons((unsigned short)port);
269 a = (unsigned char *)&address->addr.in.sin_addr;
274 #ifdef STANDALONETEST
275 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
276 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %s\n", string, string2);
280 for (i = 0;i < MAX_NAMECACHE;i++)
281 if (!strcmp(namecache[i].name, name))
283 #ifdef STANDALONETEST
284 if (i < MAX_NAMECACHE)
286 if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
289 *address = namecache[i].address;
290 address->port = port;
291 if (address->addresstype == LHNETADDRESSTYPE_INET6)
293 address->addr.in6.sin6_port = htons((unsigned short)port);
296 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
298 address->addr.in.sin_port = htons((unsigned short)port);
304 for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
305 namecache[namecacheposition].name[i] = name[i];
306 namecache[namecacheposition].name[i] = 0;
307 #ifndef STANDALONETEST
308 namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
311 // try resolving the address (handles dns and other ip formats)
312 resolved = LHNETADDRESS_Resolve(address, name, port);
315 #ifdef STANDALONETEST
316 const char *protoname;
318 switch (address->addresstype)
320 case LHNETADDRESSTYPE_INET6:
323 case LHNETADDRESSTYPE_INET4:
327 protoname = "UNKNOWN";
330 LHNETADDRESS_ToString(vaddress, string2, sizeof(string2), 1);
331 Con_Printf("LHNETADDRESS_Resolve(\"%s\") returned %s address %s\n", string, protoname, string2);
333 namecache[namecacheposition].address = *address;
337 #ifdef STANDALONETEST
338 printf("name resolution failed on address \"%s\"\n", name);
340 namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
343 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
347 int LHNETADDRESS_ToString(const lhnetaddress_t *vaddress, char *string, int stringbuffersize, int includeport)
349 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
350 const unsigned char *a;
352 if (!address || !string || stringbuffersize < 1)
354 switch(address->addresstype)
358 case LHNETADDRESSTYPE_LOOP:
361 if (stringbuffersize >= 12)
363 dpsnprintf(string, stringbuffersize, "local:%d", address->port);
369 if (stringbuffersize >= 6)
371 memcpy(string, "local", 6);
376 case LHNETADDRESSTYPE_INET4:
377 a = (const unsigned char *)(&address->addr.in.sin_addr);
380 if (stringbuffersize >= 22)
382 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d:%d", a[0], a[1], a[2], a[3], address->port);
388 if (stringbuffersize >= 16)
390 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
395 case LHNETADDRESSTYPE_INET6:
396 a = (const unsigned char *)(&address->addr.in6.sin6_addr);
399 if (stringbuffersize >= 88)
401 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);
407 if (stringbuffersize >= 80)
409 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]);
418 int LHNETADDRESS_GetAddressType(const lhnetaddress_t *address)
421 return address->addresstype;
423 return LHNETADDRESSTYPE_NONE;
426 const char *LHNETADDRESS_GetInterfaceName(const lhnetaddress_t *vaddress)
428 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
430 if (address && address->addresstype == LHNETADDRESSTYPE_INET6)
434 static char ifname [IF_NAMESIZE];
436 if (if_indextoname(address->addr.in6.sin6_scope_id, ifname) == ifname)
441 // The Win32 API doesn't have if_indextoname() until Windows Vista,
442 // but luckily it just uses the interface ID as the interface name
444 static char ifname [16];
446 if (dpsnprintf(ifname, sizeof(ifname), "%lu", address->addr.in6.sin6_scope_id) > 0)
455 int LHNETADDRESS_GetPort(const lhnetaddress_t *address)
459 return address->port;
462 int LHNETADDRESS_SetPort(lhnetaddress_t *vaddress, int port)
464 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
467 address->port = port;
468 switch(address->addresstype)
470 case LHNETADDRESSTYPE_LOOP:
472 case LHNETADDRESSTYPE_INET4:
473 address->addr.in.sin_port = htons((unsigned short)port);
475 case LHNETADDRESSTYPE_INET6:
476 address->addr.in6.sin6_port = htons((unsigned short)port);
483 int LHNETADDRESS_Compare(const lhnetaddress_t *vaddress1, const lhnetaddress_t *vaddress2)
485 lhnetaddressnative_t *address1 = (lhnetaddressnative_t *)vaddress1;
486 lhnetaddressnative_t *address2 = (lhnetaddressnative_t *)vaddress2;
487 if (!address1 || !address2)
489 if (address1->addresstype != address2->addresstype)
491 switch(address1->addresstype)
493 case LHNETADDRESSTYPE_LOOP:
494 if (address1->port != address2->port)
497 case LHNETADDRESSTYPE_INET4:
498 if (address1->addr.in.sin_family != address2->addr.in.sin_family)
500 if (memcmp(&address1->addr.in.sin_addr, &address2->addr.in.sin_addr, sizeof(address1->addr.in.sin_addr)))
502 if (address1->port != address2->port)
505 case LHNETADDRESSTYPE_INET6:
506 if (address1->addr.in6.sin6_family != address2->addr.in6.sin6_family)
508 if (memcmp(&address1->addr.in6.sin6_addr, &address2->addr.in6.sin6_addr, sizeof(address1->addr.in6.sin6_addr)))
510 if (address1->port != address2->port)
518 typedef struct lhnetpacket_s
525 #ifndef STANDALONETEST
526 double sentdoubletime;
528 struct lhnetpacket_s *next, *prev;
532 static int lhnet_active;
533 static lhnetsocket_t lhnet_socketlist;
534 static lhnetpacket_t lhnet_packetlist;
536 static int lhnet_didWSAStartup = 0;
537 static WSADATA lhnet_winsockdata;
540 void LHNET_Init(void)
544 lhnet_socketlist.next = lhnet_socketlist.prev = &lhnet_socketlist;
545 lhnet_packetlist.next = lhnet_packetlist.prev = &lhnet_packetlist;
548 lhnet_didWSAStartup = !WSAStartup(MAKEWORD(1, 1), &lhnet_winsockdata);
549 if (!lhnet_didWSAStartup)
550 Con_Print("LHNET_Init: WSAStartup failed, networking disabled\n");
554 void LHNET_Shutdown(void)
559 while (lhnet_socketlist.next != &lhnet_socketlist)
560 LHNET_CloseSocket(lhnet_socketlist.next);
561 while (lhnet_packetlist.next != &lhnet_packetlist)
563 p = lhnet_packetlist.next;
564 p->prev->next = p->next;
565 p->next->prev = p->prev;
569 if (lhnet_didWSAStartup)
571 lhnet_didWSAStartup = 0;
578 static const char *LHNETPRIVATE_StrError(void)
581 int i = WSAGetLastError();
584 case WSAEINTR: return "WSAEINTR";
585 case WSAEBADF: return "WSAEBADF";
586 case WSAEACCES: return "WSAEACCES";
587 case WSAEFAULT: return "WSAEFAULT";
588 case WSAEINVAL: return "WSAEINVAL";
589 case WSAEMFILE: return "WSAEMFILE";
590 case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK";
591 case WSAEINPROGRESS: return "WSAEINPROGRESS";
592 case WSAEALREADY: return "WSAEALREADY";
593 case WSAENOTSOCK: return "WSAENOTSOCK";
594 case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ";
595 case WSAEMSGSIZE: return "WSAEMSGSIZE";
596 case WSAEPROTOTYPE: return "WSAEPROTOTYPE";
597 case WSAENOPROTOOPT: return "WSAENOPROTOOPT";
598 case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
599 case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
600 case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP";
601 case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT";
602 case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT";
603 case WSAEADDRINUSE: return "WSAEADDRINUSE";
604 case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL";
605 case WSAENETDOWN: return "WSAENETDOWN";
606 case WSAENETUNREACH: return "WSAENETUNREACH";
607 case WSAENETRESET: return "WSAENETRESET";
608 case WSAECONNABORTED: return "WSAECONNABORTED";
609 case WSAECONNRESET: return "WSAECONNRESET";
610 case WSAENOBUFS: return "WSAENOBUFS";
611 case WSAEISCONN: return "WSAEISCONN";
612 case WSAENOTCONN: return "WSAENOTCONN";
613 case WSAESHUTDOWN: return "WSAESHUTDOWN";
614 case WSAETOOMANYREFS: return "WSAETOOMANYREFS";
615 case WSAETIMEDOUT: return "WSAETIMEDOUT";
616 case WSAECONNREFUSED: return "WSAECONNREFUSED";
617 case WSAELOOP: return "WSAELOOP";
618 case WSAENAMETOOLONG: return "WSAENAMETOOLONG";
619 case WSAEHOSTDOWN: return "WSAEHOSTDOWN";
620 case WSAEHOSTUNREACH: return "WSAEHOSTUNREACH";
621 case WSAENOTEMPTY: return "WSAENOTEMPTY";
622 case WSAEPROCLIM: return "WSAEPROCLIM";
623 case WSAEUSERS: return "WSAEUSERS";
624 case WSAEDQUOT: return "WSAEDQUOT";
625 case WSAESTALE: return "WSAESTALE";
626 case WSAEREMOTE: return "WSAEREMOTE";
627 case WSAEDISCON: return "WSAEDISCON";
628 case 0: return "no error";
629 default: return "unknown WSAE error";
632 return strerror(errno);
636 void LHNET_SleepUntilPacket_Microseconds(int microseconds)
644 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
646 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
648 if (lastfd < s->inetsocket)
649 lastfd = s->inetsocket;
650 FD_SET((unsigned int)s->inetsocket, &fdreadset);
653 tv.tv_sec = microseconds / 1000000;
654 tv.tv_usec = microseconds % 1000000;
655 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
658 lhnetsocket_t *LHNET_OpenSocket_Connectionless(lhnetaddress_t *address)
660 lhnetsocket_t *lhnetsocket, *s;
663 lhnetsocket = (lhnetsocket_t *)Z_Malloc(sizeof(*lhnetsocket));
666 memset(lhnetsocket, 0, sizeof(*lhnetsocket));
667 lhnetsocket->address = *address;
668 switch(lhnetsocket->address.addresstype)
670 case LHNETADDRESSTYPE_LOOP:
671 if (lhnetsocket->address.port == 0)
673 // allocate a port dynamically
674 // this search will always terminate because there is never
675 // an allocated socket with port 0, so if the number wraps it
676 // will find the port is unused, and then refuse to use port
677 // 0, causing an intentional failure condition
678 lhnetsocket->address.port = 1024;
681 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
682 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
684 if (s == &lhnet_socketlist)
686 lhnetsocket->address.port++;
689 // check if the port is available
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 && lhnetsocket->address.port != 0)
695 lhnetsocket->next = &lhnet_socketlist;
696 lhnetsocket->prev = lhnetsocket->next->prev;
697 lhnetsocket->next->prev = lhnetsocket;
698 lhnetsocket->prev->next = lhnetsocket;
702 case LHNETADDRESSTYPE_INET4:
703 case LHNETADDRESSTYPE_INET6:
705 if (lhnet_didWSAStartup)
708 if ((lhnetsocket->inetsocket = socket(address->addresstype == LHNETADDRESSTYPE_INET6 ? PF_INET6 : PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1)
716 if (ioctlsocket(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
719 // We need to set this flag to tell the OS that we only listen on IPv6. If we don't
720 // most OSes will create a dual-protocol socket that also listens on IPv4. In this case
721 // if an IPv4 socket is already bound to the port we want, our bind() call will fail.
723 if (address->addresstype != LHNETADDRESSTYPE_INET6
724 || setsockopt (lhnetsocket->inetsocket, IPPROTO_IPV6, IPV6_V6ONLY,
725 (const void *)&ipv6_only, sizeof(ipv6_only)) == 0
727 // The Win32 API only supports IPV6_V6ONLY since Windows Vista, but fortunately
728 // the default value is what we want on Win32 anyway (IPV6_V6ONLY = true)
729 || SOCKETERRNO == WSAENOPROTOOPT
734 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
737 if (address->addresstype == LHNETADDRESSTYPE_INET6)
739 namelen = sizeof(localaddress->addr.in6);
740 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
741 if (bindresult != -1)
742 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
746 namelen = sizeof(localaddress->addr.in);
747 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
748 if (bindresult != -1)
749 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
751 if (bindresult != -1)
754 // enable broadcast on this socket
755 setsockopt(lhnetsocket->inetsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i));
756 lhnetsocket->next = &lhnet_socketlist;
757 lhnetsocket->prev = lhnetsocket->next->prev;
758 lhnetsocket->next->prev = lhnetsocket;
759 lhnetsocket->prev->next = lhnetsocket;
761 if (ioctlsocket(lhnetsocket->inetsocket, SIO_UDP_CONNRESET, &_false) == -1)
762 Con_DPrintf("LHNET_OpenSocket_Connectionless: ioctlsocket SIO_UDP_CONNRESET returned error: %s\n", LHNETPRIVATE_StrError());
767 Con_Printf("LHNET_OpenSocket_Connectionless: bind returned error: %s\n", LHNETPRIVATE_StrError());
771 Con_Printf("LHNET_OpenSocket_Connectionless: setsockopt(IPV6_V6ONLY) returned error: %s\n", LHNETPRIVATE_StrError());
775 Con_Printf("LHNET_OpenSocket_Connectionless: ioctlsocket returned error: %s\n", LHNETPRIVATE_StrError());
776 closesocket(lhnetsocket->inetsocket);
779 Con_Printf("LHNET_OpenSocket_Connectionless: socket returned error: %s\n", LHNETPRIVATE_StrError());
783 Con_Print("LHNET_OpenSocket_Connectionless: can't open a socket (WSAStartup failed during LHNET_Init)\n");
794 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
798 // unlink from socket list
799 if (lhnetsocket->next == NULL)
801 lhnetsocket->next->prev = lhnetsocket->prev;
802 lhnetsocket->prev->next = lhnetsocket->next;
803 lhnetsocket->next = NULL;
804 lhnetsocket->prev = NULL;
806 // no special close code for loopback, just inet
807 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
809 closesocket(lhnetsocket->inetsocket);
815 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
818 return &sock->address;
823 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *vaddress)
825 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
827 if (!lhnetsocket || !address || !content || maxcontentlength < 1)
829 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
832 lhnetpacket_t *p, *pnext;
833 // scan for any old packets to timeout while searching for a packet
834 // that is waiting to be delivered to this socket
835 currenttime = time(NULL);
836 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
839 if (p->timeout < currenttime)
842 p->next->prev = p->prev;
843 p->prev->next = p->next;
847 #ifndef STANDALONETEST
848 if (cl_netlocalping.value && (realtime - cl_netlocalping.value * (1.0 / 2000.0)) < p->sentdoubletime)
851 if (value == 0 && p->destinationport == lhnetsocket->address.port)
853 if (p->length <= maxcontentlength)
855 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
856 *address = *localaddress;
857 address->port = p->sourceport;
858 memcpy(content, p->data, p->length);
864 p->next->prev = p->prev;
865 p->prev->next = p->next;
870 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
872 unsigned int inetaddresslength;
873 address->addresstype = LHNETADDRESSTYPE_NONE;
874 inetaddresslength = sizeof(address->addr.in);
875 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, &address->addr.sock, &inetaddresslength);
878 address->addresstype = LHNETADDRESSTYPE_INET4;
879 address->port = ntohs(address->addr.in.sin_port);
882 else if (value == -1)
885 if (e == EWOULDBLOCK)
890 Con_Print("Connection refused\n");
893 Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
896 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
898 unsigned int inetaddresslength;
899 address->addresstype = LHNETADDRESSTYPE_NONE;
900 inetaddresslength = sizeof(address->addr.in6);
901 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, &address->addr.sock, &inetaddresslength);
904 address->addresstype = LHNETADDRESSTYPE_INET6;
905 address->port = ntohs(address->addr.in6.sin6_port);
908 else if (value == -1)
911 if (e == EWOULDBLOCK)
916 Con_Print("Connection refused\n");
919 Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
925 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *vaddress)
927 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
929 if (!lhnetsocket || !address || !content || contentlength < 1)
931 if (lhnetsocket->address.addresstype != address->addresstype)
933 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
936 p = (lhnetpacket_t *)Z_Malloc(sizeof(*p) + contentlength);
937 p->data = (void *)(p + 1);
938 memcpy(p->data, content, contentlength);
939 p->length = contentlength;
940 p->sourceport = lhnetsocket->address.port;
941 p->destinationport = address->port;
942 p->timeout = time(NULL) + 10;
943 p->next = &lhnet_packetlist;
944 p->prev = p->next->prev;
947 #ifndef STANDALONETEST
948 p->sentdoubletime = realtime;
950 value = contentlength;
952 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
954 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addr.in, sizeof(struct sockaddr_in));
957 if (SOCKETERRNO == EWOULDBLOCK)
959 Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
962 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
964 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addr.in6, sizeof(struct sockaddr_in6));
967 if (SOCKETERRNO == EWOULDBLOCK)
969 Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
975 #ifdef STANDALONETEST
976 int main(int argc, char **argv)
979 char *buffer = "test", buffer2[1024];
980 int blen = strlen(buffer);
982 lhnetsocket_t *sock1;
983 lhnetsocket_t *sock2;
984 lhnetaddress_t myaddy1;
985 lhnetaddress_t myaddy2;
986 lhnetaddress_t myaddy3;
987 lhnetaddress_t localhostaddy1;
988 lhnetaddress_t localhostaddy2;
992 printf("calling LHNET_Init\n");
995 printf("calling LHNET_FromPort twice to create two local addresses\n");
996 LHNETADDRESS_FromPort(&myaddy1, LHNETADDRESSTYPE_INET4, 4000);
997 LHNETADDRESS_FromPort(&myaddy2, LHNETADDRESSTYPE_INET4, 4001);
998 LHNETADDRESS_FromString(&localhostaddy1, "127.0.0.1", 4000);
999 LHNETADDRESS_FromString(&localhostaddy2, "127.0.0.1", 4001);
1001 printf("calling LHNET_OpenSocket_Connectionless twice to create two local sockets\n");
1002 sock1 = LHNET_OpenSocket_Connectionless(&myaddy1);
1003 sock2 = LHNET_OpenSocket_Connectionless(&myaddy2);
1005 printf("calling LHNET_Write to send a packet from the first socket to the second socket\n");
1006 test1 = LHNET_Write(sock1, buffer, blen, &localhostaddy2);
1007 printf("sleeping briefly\n");
1013 printf("calling LHNET_Read on the second socket to read the packet sent from the first socket\n");
1014 test2 = LHNET_Read(sock2, buffer2, b2len - 1, &myaddy3);
1016 Con_Printf("socket to socket test succeeded\n");
1018 Con_Printf("socket to socket test failed\n");
1021 printf("press any key to exit\n");
1025 printf("calling LHNET_Shutdown\n");
1027 printf("exiting\n");
1030 lhnetsocket_t *sock[16], *sendsock;
1039 int sendmessagelength;
1040 lhnetaddress_t destaddress;
1041 lhnetaddress_t receiveaddress;
1042 lhnetaddress_t sockaddress[16];
1043 char buffer[1536], addressstring[128], addressstring2[128];
1044 if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
1046 printf("calling LHNET_Init()\n");
1050 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
1051 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
1052 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
1056 sendmessagelength = 0;
1058 for (i = 0;i < numsockets;i++)
1060 LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
1061 printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
1062 if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
1064 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1065 printf("opened socket successfully (address \"%s\")\n", addressstring2);
1069 printf("failed to open socket\n");
1080 count = atoi(argv[2]);
1081 if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
1083 sendmessage = argv[4];
1084 sendmessagelength = strlen(sendmessage);
1086 for (i = 0;i < numsockets;i++)
1087 if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
1089 if (sendsock == NULL)
1091 printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
1097 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
1101 printf("started, now listening for \"exit\" on the opened sockets\n");
1102 oldtime = time(NULL);
1110 for (i = 0;i < numsockets;i++)
1114 length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
1116 printf("localsock read error: length < 0");
1117 else if (length > 0 && length < (int)sizeof(buffer))
1120 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
1121 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1122 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
1123 if (!strcmp(buffer, "exit"))
1130 if (argc == 5 && count > 0)
1132 newtime = time(NULL);
1133 if (newtime != oldtime)
1135 LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
1136 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
1137 printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
1138 length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
1139 if (length == sendmessagelength)
1140 printf("sent successfully\n");
1142 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
1146 printf("Done sending, still listening for \"exit\"\n");
1150 for (i = 0;i < numsockets;i++)
1154 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1155 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
1156 LHNET_CloseSocket(sock[i]);
1159 printf("calling LHNET_Shutdown()\n");
1163 printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");