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
10 #ifndef STANDALONETEST
20 #include <sys/types.h>
21 #include <sys/socket.h>
22 #include <sys/ioctl.h>
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
31 #include <proto/socket.h>
34 // for Z_Malloc/Z_Free in quake
35 #ifndef STANDALONETEST
40 #define Con_Print printf
41 #define Con_Printf printf
42 #define Z_Malloc malloc
49 #define EWOULDBLOCK WSAEWOULDBLOCK
50 #define ECONNREFUSED WSAECONNREFUSED
52 #define SOCKETERRNO WSAGetLastError()
54 #define IOC_VENDOR 0x18000000
55 #define _WSAIOW(x,y) (IOC_IN|(x)|(y))
56 #define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
59 #elif defined(__MORPHOS__)
60 #define ioctlsocket IoctlSocket
61 #define closesocket CloseSocket
62 #define SOCKETERRNO Errno()
66 #define ioctlsocket ioctl
67 #define closesocket close
68 #define SOCKETERRNO errno
70 #define SOCKLEN_T socklen_t
73 typedef struct lhnetaddressnative_s
75 lhnetaddresstype_t addresstype;
80 struct sockaddr_in in;
81 struct sockaddr_in6 in6;
87 // to make LHNETADDRESS_FromString resolve repeated hostnames faster, cache them
88 #define MAX_NAMECACHE 64
89 static struct namecache_s
91 lhnetaddressnative_t address;
92 double expirationtime;
95 namecache[MAX_NAMECACHE];
96 static int namecacheposition = 0;
98 int LHNETADDRESS_FromPort(lhnetaddress_t *vaddress, lhnetaddresstype_t addresstype, int port)
100 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
107 case LHNETADDRESSTYPE_LOOP:
108 // local:port (loopback)
109 memset(address, 0, sizeof(*address));
110 address->addresstype = LHNETADDRESSTYPE_LOOP;
111 address->port = port;
113 case LHNETADDRESSTYPE_INET4:
114 // 0.0.0.0:port (INADDR_ANY, binds to all interfaces)
115 memset(address, 0, sizeof(*address));
116 address->addresstype = LHNETADDRESSTYPE_INET4;
117 address->port = port;
118 address->addr.in.sin_family = AF_INET;
119 address->addr.in.sin_port = htons((unsigned short)port);
121 case LHNETADDRESSTYPE_INET6:
122 // [0:0:0:0:0:0:0:0]:port (IN6ADDR_ANY, binds to all interfaces)
123 memset(address, 0, sizeof(*address));
124 address->addresstype = LHNETADDRESSTYPE_INET6;
125 address->port = port;
126 address->addr.in6.sin6_family = AF_INET6;
127 address->addr.in6.sin6_port = htons((unsigned short)port);
133 int LHNETADDRESS_Resolve(lhnetaddressnative_t *address, const char *name, int port)
136 struct addrinfo hints;
137 struct addrinfo* addrinf;
140 dpsnprintf (port_buff, sizeof (port_buff), "%d", port);
141 port_buff[sizeof (port_buff) - 1] = '\0';
143 memset(&hints, 0, sizeof (hints));
144 hints.ai_family = AF_UNSPEC;
145 hints.ai_socktype = SOCK_DGRAM;
146 //hints.ai_flags = AI_PASSIVE;
148 err = getaddrinfo(name, port_buff, &hints, &addrinf);
149 if (err != 0 || addrinf == NULL)
151 if (addrinf->ai_addr->sa_family != AF_INET6 && addrinf->ai_addr->sa_family != AF_INET)
155 if (addrinf->ai_addr->sa_family == AF_INET6)
157 address->addresstype = LHNETADDRESSTYPE_INET6;
158 memcpy(&address->addr.in6, addrinf->ai_addr, sizeof(address->addr.in6));
162 address->addresstype = LHNETADDRESSTYPE_INET4;
163 memcpy(&address->addr.in, addrinf->ai_addr, sizeof(address->addr.in));
165 address->port = port;
167 freeaddrinfo (addrinf);
171 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
173 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
174 int i, port, d1, d2, d3, d4, resolved;
178 #ifdef STANDALONETEST
181 const char* addr_start;
182 const char* addr_end = NULL;
183 const char* port_name = NULL;
184 int addr_family = AF_UNSPEC;
186 if (!address || !string || !*string)
188 memset(address, 0, sizeof(*address));
189 address->addresstype = LHNETADDRESSTYPE_NONE;
192 // If it's a bracketed IPv6 address
193 if (string[0] == '[')
195 const char* end_bracket = strchr(string, ']');
197 if (end_bracket == NULL)
200 if (end_bracket[1] == ':')
201 port_name = end_bracket + 2;
202 else if (end_bracket[1] != '\0')
205 addr_family = AF_INET6;
206 addr_start = &string[1];
207 addr_end = end_bracket;
211 const char* first_colon;
215 // If it's a numeric non-bracket IPv6 address (-> no port),
216 // or it's a numeric IPv4 address, or a name, with a port
217 first_colon = strchr(string, ':');
218 if (first_colon != NULL)
220 const char* last_colon = strrchr(first_colon + 1, ':');
222 // If it's an numeric IPv4 address, or a name, with a port
223 if (last_colon == NULL)
225 addr_end = first_colon;
226 port_name = first_colon + 1;
229 addr_family = AF_INET6;
233 if (addr_end != NULL)
234 namelen = addr_end - addr_start;
236 namelen = strlen (addr_start);
238 if (namelen >= sizeof(name))
239 namelen = sizeof(name) - 1;
240 memcpy (name, addr_start, namelen);
244 port = atoi(port_name);
250 if (!strcmp(name, "local"))
252 address->addresstype = LHNETADDRESSTYPE_LOOP;
253 address->port = port;
256 // try to parse as dotted decimal ipv4 address first
257 // note this supports partial ip addresses
258 d1 = d2 = d3 = d4 = 0;
260 #define sscanf sscanf_s
262 if (addr_family != AF_INET6 &&
263 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)
265 // parsed a valid ipv4 address
266 address->addresstype = LHNETADDRESSTYPE_INET4;
267 address->port = port;
268 address->addr.in.sin_family = AF_INET;
269 address->addr.in.sin_port = htons((unsigned short)port);
270 a = (unsigned char *)&address->addr.in.sin_addr;
275 #ifdef STANDALONETEST
276 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
277 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %s\n", string, string2);
281 for (i = 0;i < MAX_NAMECACHE;i++)
282 if (!strcmp(namecache[i].name, name))
284 #ifdef STANDALONETEST
285 if (i < MAX_NAMECACHE)
287 if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
290 *address = namecache[i].address;
291 address->port = port;
292 if (address->addresstype == LHNETADDRESSTYPE_INET6)
294 address->addr.in6.sin6_port = htons((unsigned short)port);
297 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
299 address->addr.in.sin_port = htons((unsigned short)port);
305 for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
306 namecache[namecacheposition].name[i] = name[i];
307 namecache[namecacheposition].name[i] = 0;
308 #ifndef STANDALONETEST
309 namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
312 // try resolving the address (handles dns and other ip formats)
313 resolved = LHNETADDRESS_Resolve(address, name, port);
316 #ifdef STANDALONETEST
317 const char *protoname;
319 switch (address->addresstype)
321 case LHNETADDRESSTYPE_INET6:
324 case LHNETADDRESSTYPE_INET4:
328 protoname = "UNKNOWN";
331 LHNETADDRESS_ToString(vaddress, string2, sizeof(string2), 1);
332 Con_Printf("LHNETADDRESS_Resolve(\"%s\") returned %s address %s\n", string, protoname, string2);
334 namecache[namecacheposition].address = *address;
338 #ifdef STANDALONETEST
339 printf("name resolution failed on address \"%s\"\n", name);
341 namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
344 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
348 int LHNETADDRESS_ToString(const lhnetaddress_t *vaddress, char *string, int stringbuffersize, int includeport)
350 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
351 const unsigned char *a;
353 if (!address || !string || stringbuffersize < 1)
355 switch(address->addresstype)
359 case LHNETADDRESSTYPE_LOOP:
362 if (stringbuffersize >= 12)
364 dpsnprintf(string, stringbuffersize, "local:%d", address->port);
370 if (stringbuffersize >= 6)
372 memcpy(string, "local", 6);
377 case LHNETADDRESSTYPE_INET4:
378 a = (const unsigned char *)(&address->addr.in.sin_addr);
381 if (stringbuffersize >= 22)
383 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d:%d", a[0], a[1], a[2], a[3], address->port);
389 if (stringbuffersize >= 16)
391 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
396 case LHNETADDRESSTYPE_INET6:
397 a = (const unsigned char *)(&address->addr.in6.sin6_addr);
400 if (stringbuffersize >= 88)
402 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);
408 if (stringbuffersize >= 80)
410 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]);
419 int LHNETADDRESS_GetAddressType(const lhnetaddress_t *address)
422 return address->addresstype;
424 return LHNETADDRESSTYPE_NONE;
427 const char *LHNETADDRESS_GetInterfaceName(const lhnetaddress_t *vaddress)
429 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
431 if (address && address->addresstype == LHNETADDRESSTYPE_INET6)
435 static char ifname [IF_NAMESIZE];
437 if (if_indextoname(address->addr.in6.sin6_scope_id, ifname) == ifname)
442 // The Win32 API doesn't have if_indextoname() until Windows Vista,
443 // but luckily it just uses the interface ID as the interface name
445 static char ifname [16];
447 if (dpsnprintf(ifname, sizeof(ifname), "%lu", address->addr.in6.sin6_scope_id) > 0)
456 int LHNETADDRESS_GetPort(const lhnetaddress_t *address)
460 return address->port;
463 int LHNETADDRESS_SetPort(lhnetaddress_t *vaddress, int port)
465 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
468 address->port = port;
469 switch(address->addresstype)
471 case LHNETADDRESSTYPE_LOOP:
473 case LHNETADDRESSTYPE_INET4:
474 address->addr.in.sin_port = htons((unsigned short)port);
476 case LHNETADDRESSTYPE_INET6:
477 address->addr.in6.sin6_port = htons((unsigned short)port);
484 int LHNETADDRESS_Compare(const lhnetaddress_t *vaddress1, const lhnetaddress_t *vaddress2)
486 lhnetaddressnative_t *address1 = (lhnetaddressnative_t *)vaddress1;
487 lhnetaddressnative_t *address2 = (lhnetaddressnative_t *)vaddress2;
488 if (!address1 || !address2)
490 if (address1->addresstype != address2->addresstype)
492 switch(address1->addresstype)
494 case LHNETADDRESSTYPE_LOOP:
495 if (address1->port != address2->port)
498 case LHNETADDRESSTYPE_INET4:
499 if (address1->addr.in.sin_family != address2->addr.in.sin_family)
501 if (memcmp(&address1->addr.in.sin_addr, &address2->addr.in.sin_addr, sizeof(address1->addr.in.sin_addr)))
503 if (address1->port != address2->port)
506 case LHNETADDRESSTYPE_INET6:
507 if (address1->addr.in6.sin6_family != address2->addr.in6.sin6_family)
509 if (memcmp(&address1->addr.in6.sin6_addr, &address2->addr.in6.sin6_addr, sizeof(address1->addr.in6.sin6_addr)))
511 if (address1->port != address2->port)
519 typedef struct lhnetpacket_s
526 #ifndef STANDALONETEST
527 double sentdoubletime;
529 struct lhnetpacket_s *next, *prev;
533 static int lhnet_active;
534 static lhnetsocket_t lhnet_socketlist;
535 static lhnetpacket_t lhnet_packetlist;
537 static int lhnet_didWSAStartup = 0;
538 static WSADATA lhnet_winsockdata;
541 void LHNET_Init(void)
545 lhnet_socketlist.next = lhnet_socketlist.prev = &lhnet_socketlist;
546 lhnet_packetlist.next = lhnet_packetlist.prev = &lhnet_packetlist;
549 lhnet_didWSAStartup = !WSAStartup(MAKEWORD(1, 1), &lhnet_winsockdata);
550 if (!lhnet_didWSAStartup)
551 Con_Print("LHNET_Init: WSAStartup failed, networking disabled\n");
555 void LHNET_Shutdown(void)
560 while (lhnet_socketlist.next != &lhnet_socketlist)
561 LHNET_CloseSocket(lhnet_socketlist.next);
562 while (lhnet_packetlist.next != &lhnet_packetlist)
564 p = lhnet_packetlist.next;
565 p->prev->next = p->next;
566 p->next->prev = p->prev;
570 if (lhnet_didWSAStartup)
572 lhnet_didWSAStartup = 0;
579 static const char *LHNETPRIVATE_StrError(void)
582 int i = WSAGetLastError();
585 case WSAEINTR: return "WSAEINTR";
586 case WSAEBADF: return "WSAEBADF";
587 case WSAEACCES: return "WSAEACCES";
588 case WSAEFAULT: return "WSAEFAULT";
589 case WSAEINVAL: return "WSAEINVAL";
590 case WSAEMFILE: return "WSAEMFILE";
591 case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK";
592 case WSAEINPROGRESS: return "WSAEINPROGRESS";
593 case WSAEALREADY: return "WSAEALREADY";
594 case WSAENOTSOCK: return "WSAENOTSOCK";
595 case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ";
596 case WSAEMSGSIZE: return "WSAEMSGSIZE";
597 case WSAEPROTOTYPE: return "WSAEPROTOTYPE";
598 case WSAENOPROTOOPT: return "WSAENOPROTOOPT";
599 case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
600 case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
601 case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP";
602 case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT";
603 case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT";
604 case WSAEADDRINUSE: return "WSAEADDRINUSE";
605 case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL";
606 case WSAENETDOWN: return "WSAENETDOWN";
607 case WSAENETUNREACH: return "WSAENETUNREACH";
608 case WSAENETRESET: return "WSAENETRESET";
609 case WSAECONNABORTED: return "WSAECONNABORTED";
610 case WSAECONNRESET: return "WSAECONNRESET";
611 case WSAENOBUFS: return "WSAENOBUFS";
612 case WSAEISCONN: return "WSAEISCONN";
613 case WSAENOTCONN: return "WSAENOTCONN";
614 case WSAESHUTDOWN: return "WSAESHUTDOWN";
615 case WSAETOOMANYREFS: return "WSAETOOMANYREFS";
616 case WSAETIMEDOUT: return "WSAETIMEDOUT";
617 case WSAECONNREFUSED: return "WSAECONNREFUSED";
618 case WSAELOOP: return "WSAELOOP";
619 case WSAENAMETOOLONG: return "WSAENAMETOOLONG";
620 case WSAEHOSTDOWN: return "WSAEHOSTDOWN";
621 case WSAEHOSTUNREACH: return "WSAEHOSTUNREACH";
622 case WSAENOTEMPTY: return "WSAENOTEMPTY";
623 case WSAEPROCLIM: return "WSAEPROCLIM";
624 case WSAEUSERS: return "WSAEUSERS";
625 case WSAEDQUOT: return "WSAEDQUOT";
626 case WSAESTALE: return "WSAESTALE";
627 case WSAEREMOTE: return "WSAEREMOTE";
628 case WSAEDISCON: return "WSAEDISCON";
629 case 0: return "no error";
630 default: return "unknown WSAE error";
633 return strerror(errno);
637 void LHNET_SleepUntilPacket_Microseconds(int microseconds)
645 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
647 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
649 if (lastfd < s->inetsocket)
650 lastfd = s->inetsocket;
651 FD_SET((unsigned int)s->inetsocket, &fdreadset);
654 tv.tv_sec = microseconds / 1000000;
655 tv.tv_usec = microseconds % 1000000;
656 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
659 lhnetsocket_t *LHNET_OpenSocket_Connectionless(lhnetaddress_t *address)
661 lhnetsocket_t *lhnetsocket, *s;
664 lhnetsocket = (lhnetsocket_t *)Z_Malloc(sizeof(*lhnetsocket));
667 memset(lhnetsocket, 0, sizeof(*lhnetsocket));
668 lhnetsocket->address = *address;
669 switch(lhnetsocket->address.addresstype)
671 case LHNETADDRESSTYPE_LOOP:
672 if (lhnetsocket->address.port == 0)
674 // allocate a port dynamically
675 // this search will always terminate because there is never
676 // an allocated socket with port 0, so if the number wraps it
677 // will find the port is unused, and then refuse to use port
678 // 0, causing an intentional failure condition
679 lhnetsocket->address.port = 1024;
682 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
683 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
685 if (s == &lhnet_socketlist)
687 lhnetsocket->address.port++;
690 // check if the port is available
691 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
692 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
694 if (s == &lhnet_socketlist && lhnetsocket->address.port != 0)
696 lhnetsocket->next = &lhnet_socketlist;
697 lhnetsocket->prev = lhnetsocket->next->prev;
698 lhnetsocket->next->prev = lhnetsocket;
699 lhnetsocket->prev->next = lhnetsocket;
703 case LHNETADDRESSTYPE_INET4:
704 case LHNETADDRESSTYPE_INET6:
706 if (lhnet_didWSAStartup)
709 if ((lhnetsocket->inetsocket = socket(address->addresstype == LHNETADDRESSTYPE_INET6 ? PF_INET6 : PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1)
717 if (ioctlsocket(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
720 // We need to set this flag to tell the OS that we only listen on IPv6. If we don't
721 // most OSes will create a dual-protocol socket that also listens on IPv4. In this case
722 // if an IPv4 socket is already bound to the port we want, our bind() call will fail.
724 if (address->addresstype != LHNETADDRESSTYPE_INET6
725 || setsockopt (lhnetsocket->inetsocket, IPPROTO_IPV6, IPV6_V6ONLY,
726 (const void *)&ipv6_only, sizeof(ipv6_only)) == 0
728 // The Win32 API only supports IPV6_V6ONLY since Windows Vista, but fortunately
729 // the default value is what we want on Win32 anyway (IPV6_V6ONLY = true)
730 || SOCKETERRNO == WSAENOPROTOOPT
735 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
738 if (address->addresstype == LHNETADDRESSTYPE_INET6)
740 namelen = sizeof(localaddress->addr.in6);
741 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
742 if (bindresult != -1)
743 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
747 namelen = sizeof(localaddress->addr.in);
748 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
749 if (bindresult != -1)
750 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
752 if (bindresult != -1)
755 // enable broadcast on this socket
756 setsockopt(lhnetsocket->inetsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i));
757 lhnetsocket->next = &lhnet_socketlist;
758 lhnetsocket->prev = lhnetsocket->next->prev;
759 lhnetsocket->next->prev = lhnetsocket;
760 lhnetsocket->prev->next = lhnetsocket;
762 if (ioctlsocket(lhnetsocket->inetsocket, SIO_UDP_CONNRESET, &_false) == -1)
763 Con_DPrintf("LHNET_OpenSocket_Connectionless: ioctlsocket SIO_UDP_CONNRESET returned error: %s\n", LHNETPRIVATE_StrError());
768 Con_Printf("LHNET_OpenSocket_Connectionless: bind returned error: %s\n", LHNETPRIVATE_StrError());
772 Con_Printf("LHNET_OpenSocket_Connectionless: setsockopt(IPV6_V6ONLY) returned error: %s\n", LHNETPRIVATE_StrError());
776 Con_Printf("LHNET_OpenSocket_Connectionless: ioctlsocket returned error: %s\n", LHNETPRIVATE_StrError());
777 closesocket(lhnetsocket->inetsocket);
780 Con_Printf("LHNET_OpenSocket_Connectionless: socket returned error: %s\n", LHNETPRIVATE_StrError());
784 Con_Print("LHNET_OpenSocket_Connectionless: can't open a socket (WSAStartup failed during LHNET_Init)\n");
795 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
799 // unlink from socket list
800 if (lhnetsocket->next == NULL)
802 lhnetsocket->next->prev = lhnetsocket->prev;
803 lhnetsocket->prev->next = lhnetsocket->next;
804 lhnetsocket->next = NULL;
805 lhnetsocket->prev = NULL;
807 // no special close code for loopback, just inet
808 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
810 closesocket(lhnetsocket->inetsocket);
816 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
819 return &sock->address;
824 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *vaddress)
826 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
828 if (!lhnetsocket || !address || !content || maxcontentlength < 1)
830 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
833 lhnetpacket_t *p, *pnext;
834 // scan for any old packets to timeout while searching for a packet
835 // that is waiting to be delivered to this socket
836 currenttime = time(NULL);
837 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
840 if (p->timeout < currenttime)
843 p->next->prev = p->prev;
844 p->prev->next = p->next;
848 #ifndef STANDALONETEST
849 if (cl_netlocalping.value && (realtime - cl_netlocalping.value * (1.0 / 2000.0)) < p->sentdoubletime)
852 if (value == 0 && p->destinationport == lhnetsocket->address.port)
854 if (p->length <= maxcontentlength)
856 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
857 *address = *localaddress;
858 address->port = p->sourceport;
859 memcpy(content, p->data, p->length);
865 p->next->prev = p->prev;
866 p->prev->next = p->next;
871 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
873 unsigned int inetaddresslength;
874 address->addresstype = LHNETADDRESSTYPE_NONE;
875 inetaddresslength = sizeof(address->addr.in);
876 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, &address->addr.sock, &inetaddresslength);
879 address->addresstype = LHNETADDRESSTYPE_INET4;
880 address->port = ntohs(address->addr.in.sin_port);
883 else if (value == -1)
886 if (e == EWOULDBLOCK)
891 Con_Print("Connection refused\n");
894 Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
897 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
899 unsigned int inetaddresslength;
900 address->addresstype = LHNETADDRESSTYPE_NONE;
901 inetaddresslength = sizeof(address->addr.in6);
902 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, &address->addr.sock, &inetaddresslength);
905 address->addresstype = LHNETADDRESSTYPE_INET6;
906 address->port = ntohs(address->addr.in6.sin6_port);
909 else if (value == -1)
912 if (e == EWOULDBLOCK)
917 Con_Print("Connection refused\n");
920 Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
926 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *vaddress)
928 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
930 if (!lhnetsocket || !address || !content || contentlength < 1)
932 if (lhnetsocket->address.addresstype != address->addresstype)
934 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
937 p = (lhnetpacket_t *)Z_Malloc(sizeof(*p) + contentlength);
938 p->data = (void *)(p + 1);
939 memcpy(p->data, content, contentlength);
940 p->length = contentlength;
941 p->sourceport = lhnetsocket->address.port;
942 p->destinationport = address->port;
943 p->timeout = time(NULL) + 10;
944 p->next = &lhnet_packetlist;
945 p->prev = p->next->prev;
948 #ifndef STANDALONETEST
949 p->sentdoubletime = realtime;
951 value = contentlength;
953 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
955 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addr.in, sizeof(struct sockaddr_in));
958 if (SOCKETERRNO == EWOULDBLOCK)
960 Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
963 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
965 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addr.in6, sizeof(struct sockaddr_in6));
968 if (SOCKETERRNO == EWOULDBLOCK)
970 Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
976 #ifdef STANDALONETEST
977 int main(int argc, char **argv)
980 char *buffer = "test", buffer2[1024];
981 int blen = strlen(buffer);
983 lhnetsocket_t *sock1;
984 lhnetsocket_t *sock2;
985 lhnetaddress_t myaddy1;
986 lhnetaddress_t myaddy2;
987 lhnetaddress_t myaddy3;
988 lhnetaddress_t localhostaddy1;
989 lhnetaddress_t localhostaddy2;
993 printf("calling LHNET_Init\n");
996 printf("calling LHNET_FromPort twice to create two local addresses\n");
997 LHNETADDRESS_FromPort(&myaddy1, LHNETADDRESSTYPE_INET4, 4000);
998 LHNETADDRESS_FromPort(&myaddy2, LHNETADDRESSTYPE_INET4, 4001);
999 LHNETADDRESS_FromString(&localhostaddy1, "127.0.0.1", 4000);
1000 LHNETADDRESS_FromString(&localhostaddy2, "127.0.0.1", 4001);
1002 printf("calling LHNET_OpenSocket_Connectionless twice to create two local sockets\n");
1003 sock1 = LHNET_OpenSocket_Connectionless(&myaddy1);
1004 sock2 = LHNET_OpenSocket_Connectionless(&myaddy2);
1006 printf("calling LHNET_Write to send a packet from the first socket to the second socket\n");
1007 test1 = LHNET_Write(sock1, buffer, blen, &localhostaddy2);
1008 printf("sleeping briefly\n");
1014 printf("calling LHNET_Read on the second socket to read the packet sent from the first socket\n");
1015 test2 = LHNET_Read(sock2, buffer2, b2len - 1, &myaddy3);
1017 Con_Printf("socket to socket test succeeded\n");
1019 Con_Printf("socket to socket test failed\n");
1022 printf("press any key to exit\n");
1026 printf("calling LHNET_Shutdown\n");
1028 printf("exiting\n");
1031 lhnetsocket_t *sock[16], *sendsock;
1040 int sendmessagelength;
1041 lhnetaddress_t destaddress;
1042 lhnetaddress_t receiveaddress;
1043 lhnetaddress_t sockaddress[16];
1044 char buffer[1536], addressstring[128], addressstring2[128];
1045 if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
1047 printf("calling LHNET_Init()\n");
1051 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
1052 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
1053 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
1057 sendmessagelength = 0;
1059 for (i = 0;i < numsockets;i++)
1061 LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
1062 printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
1063 if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
1065 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1066 printf("opened socket successfully (address \"%s\")\n", addressstring2);
1070 printf("failed to open socket\n");
1081 count = atoi(argv[2]);
1082 if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
1084 sendmessage = argv[4];
1085 sendmessagelength = strlen(sendmessage);
1087 for (i = 0;i < numsockets;i++)
1088 if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
1090 if (sendsock == NULL)
1092 printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
1098 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
1102 printf("started, now listening for \"exit\" on the opened sockets\n");
1103 oldtime = time(NULL);
1111 for (i = 0;i < numsockets;i++)
1115 length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
1117 printf("localsock read error: length < 0");
1118 else if (length > 0 && length < (int)sizeof(buffer))
1121 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
1122 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1123 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
1124 if (!strcmp(buffer, "exit"))
1131 if (argc == 5 && count > 0)
1133 newtime = time(NULL);
1134 if (newtime != oldtime)
1136 LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
1137 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
1138 printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
1139 length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
1140 if (length == sendmessagelength)
1141 printf("sent successfully\n");
1143 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
1147 printf("Done sending, still listening for \"exit\"\n");
1151 for (i = 0;i < numsockets;i++)
1155 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1156 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
1157 LHNET_CloseSocket(sock[i]);
1160 printf("calling LHNET_Shutdown()\n");
1164 printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");