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
12 #ifndef STANDALONETEST
22 #include <sys/types.h>
23 #include <sys/socket.h>
24 #include <sys/ioctl.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
33 #include <proto/socket.h>
36 // for Z_Malloc/Z_Free in quake
37 #ifndef STANDALONETEST
42 #define Con_Print printf
43 #define Con_Printf printf
44 #define Z_Malloc malloc
51 #define EWOULDBLOCK WSAEWOULDBLOCK
52 #define ECONNREFUSED WSAECONNREFUSED
54 #define SOCKETERRNO WSAGetLastError()
56 #define IOC_VENDOR 0x18000000
57 #define _WSAIOW(x,y) (IOC_IN|(x)|(y))
58 #define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
61 #elif defined(__MORPHOS__)
62 #define ioctlsocket IoctlSocket
63 #define closesocket CloseSocket
64 #define SOCKETERRNO Errno()
68 #define ioctlsocket ioctl
69 #define closesocket close
70 #define SOCKETERRNO errno
72 #define SOCKLEN_T socklen_t
75 typedef struct lhnetaddressnative_s
77 lhnetaddresstype_t addresstype;
82 struct sockaddr_in in;
83 struct sockaddr_in6 in6;
89 // to make LHNETADDRESS_FromString resolve repeated hostnames faster, cache them
90 #define MAX_NAMECACHE 64
91 static struct namecache_s
93 lhnetaddressnative_t address;
94 double expirationtime;
97 namecache[MAX_NAMECACHE];
98 static int namecacheposition = 0;
100 int LHNETADDRESS_FromPort(lhnetaddress_t *vaddress, lhnetaddresstype_t addresstype, int port)
102 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
109 case LHNETADDRESSTYPE_LOOP:
110 // local:port (loopback)
111 memset(address, 0, sizeof(*address));
112 address->addresstype = LHNETADDRESSTYPE_LOOP;
113 address->port = port;
115 case LHNETADDRESSTYPE_INET4:
116 // 0.0.0.0:port (INADDR_ANY, binds to all interfaces)
117 memset(address, 0, sizeof(*address));
118 address->addresstype = LHNETADDRESSTYPE_INET4;
119 address->port = port;
120 address->addr.in.sin_family = AF_INET;
121 address->addr.in.sin_port = htons((unsigned short)port);
123 case LHNETADDRESSTYPE_INET6:
124 // [0:0:0:0:0:0:0:0]:port (IN6ADDR_ANY, binds to all interfaces)
125 memset(address, 0, sizeof(*address));
126 address->addresstype = LHNETADDRESSTYPE_INET6;
127 address->port = port;
128 address->addr.in6.sin6_family = AF_INET6;
129 address->addr.in6.sin6_port = htons((unsigned short)port);
135 int LHNETADDRESS_Resolve(lhnetaddressnative_t *address, const char *name, int port)
138 struct addrinfo hints;
139 struct addrinfo* addrinf;
142 dpsnprintf (port_buff, sizeof (port_buff), "%d", port);
143 port_buff[sizeof (port_buff) - 1] = '\0';
145 memset(&hints, 0, sizeof (hints));
146 hints.ai_family = AF_UNSPEC;
147 hints.ai_socktype = SOCK_DGRAM;
148 //hints.ai_flags = AI_PASSIVE;
150 err = getaddrinfo(name, port_buff, &hints, &addrinf);
151 if (err != 0 || addrinf == NULL)
153 if (addrinf->ai_addr->sa_family != AF_INET6 && addrinf->ai_addr->sa_family != AF_INET)
155 freeaddrinfo (addrinf);
160 if (addrinf->ai_addr->sa_family == AF_INET6)
162 address->addresstype = LHNETADDRESSTYPE_INET6;
163 memcpy(&address->addr.in6, addrinf->ai_addr, sizeof(address->addr.in6));
167 address->addresstype = LHNETADDRESSTYPE_INET4;
168 memcpy(&address->addr.in, addrinf->ai_addr, sizeof(address->addr.in));
170 address->port = port;
172 freeaddrinfo (addrinf);
176 int LHNETADDRESS_FromString(lhnetaddress_t *vaddress, const char *string, int defaultport)
178 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
179 int i, port, d1, d2, d3, d4, resolved;
183 #ifdef STANDALONETEST
186 const char* addr_start;
187 const char* addr_end = NULL;
188 const char* port_name = NULL;
189 int addr_family = AF_UNSPEC;
191 if (!address || !string || !*string)
193 memset(address, 0, sizeof(*address));
194 address->addresstype = LHNETADDRESSTYPE_NONE;
197 // If it's a bracketed IPv6 address
198 if (string[0] == '[')
200 const char* end_bracket = strchr(string, ']');
202 if (end_bracket == NULL)
205 if (end_bracket[1] == ':')
206 port_name = end_bracket + 2;
207 else if (end_bracket[1] != '\0')
210 addr_family = AF_INET6;
211 addr_start = &string[1];
212 addr_end = end_bracket;
216 const char* first_colon;
220 // If it's a numeric non-bracket IPv6 address (-> no port),
221 // or it's a numeric IPv4 address, or a name, with a port
222 first_colon = strchr(string, ':');
223 if (first_colon != NULL)
225 const char* last_colon = strrchr(first_colon + 1, ':');
227 // If it's an numeric IPv4 address, or a name, with a port
228 if (last_colon == NULL)
230 addr_end = first_colon;
231 port_name = first_colon + 1;
234 addr_family = AF_INET6;
238 if (addr_end != NULL)
239 namelen = addr_end - addr_start;
241 namelen = strlen (addr_start);
243 if (namelen >= sizeof(name))
244 namelen = sizeof(name) - 1;
245 memcpy (name, addr_start, namelen);
249 port = atoi(port_name);
255 if (!strcmp(name, "local"))
257 address->addresstype = LHNETADDRESSTYPE_LOOP;
258 address->port = port;
261 // try to parse as dotted decimal ipv4 address first
262 // note this supports partial ip addresses
263 d1 = d2 = d3 = d4 = 0;
265 #define sscanf sscanf_s
267 if (addr_family != AF_INET6 &&
268 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)
270 // parsed a valid ipv4 address
271 address->addresstype = LHNETADDRESSTYPE_INET4;
272 address->port = port;
273 address->addr.in.sin_family = AF_INET;
274 address->addr.in.sin_port = htons((unsigned short)port);
275 a = (unsigned char *)&address->addr.in.sin_addr;
280 #ifdef STANDALONETEST
281 LHNETADDRESS_ToString(address, string2, sizeof(string2), 1);
282 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %s\n", string, string2);
286 for (i = 0;i < MAX_NAMECACHE;i++)
287 if (!strcmp(namecache[i].name, name))
289 #ifdef STANDALONETEST
290 if (i < MAX_NAMECACHE)
292 if (i < MAX_NAMECACHE && realtime < namecache[i].expirationtime)
295 *address = namecache[i].address;
296 address->port = port;
297 if (address->addresstype == LHNETADDRESSTYPE_INET6)
299 address->addr.in6.sin6_port = htons((unsigned short)port);
302 else if (address->addresstype == LHNETADDRESSTYPE_INET4)
304 address->addr.in.sin_port = htons((unsigned short)port);
310 for (i = 0;i < (int)sizeof(namecache[namecacheposition].name)-1 && name[i];i++)
311 namecache[namecacheposition].name[i] = name[i];
312 namecache[namecacheposition].name[i] = 0;
313 #ifndef STANDALONETEST
314 namecache[namecacheposition].expirationtime = realtime + 12 * 3600; // 12 hours
317 // try resolving the address (handles dns and other ip formats)
318 resolved = LHNETADDRESS_Resolve(address, name, port);
321 #ifdef STANDALONETEST
322 const char *protoname;
324 switch (address->addresstype)
326 case LHNETADDRESSTYPE_INET6:
329 case LHNETADDRESSTYPE_INET4:
333 protoname = "UNKNOWN";
336 LHNETADDRESS_ToString(vaddress, string2, sizeof(string2), 1);
337 Con_Printf("LHNETADDRESS_Resolve(\"%s\") returned %s address %s\n", string, protoname, string2);
339 namecache[namecacheposition].address = *address;
343 #ifdef STANDALONETEST
344 printf("name resolution failed on address \"%s\"\n", name);
346 namecache[namecacheposition].address.addresstype = LHNETADDRESSTYPE_NONE;
349 namecacheposition = (namecacheposition + 1) % MAX_NAMECACHE;
353 int LHNETADDRESS_ToString(const lhnetaddress_t *vaddress, char *string, int stringbuffersize, int includeport)
355 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
356 const unsigned char *a;
358 if (!address || !string || stringbuffersize < 1)
360 switch(address->addresstype)
364 case LHNETADDRESSTYPE_LOOP:
367 if (stringbuffersize >= 12)
369 dpsnprintf(string, stringbuffersize, "local:%d", address->port);
375 if (stringbuffersize >= 6)
377 memcpy(string, "local", 6);
382 case LHNETADDRESSTYPE_INET4:
383 a = (const unsigned char *)(&address->addr.in.sin_addr);
386 if (stringbuffersize >= 22)
388 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d:%d", a[0], a[1], a[2], a[3], address->port);
394 if (stringbuffersize >= 16)
396 dpsnprintf(string, stringbuffersize, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
401 case LHNETADDRESSTYPE_INET6:
402 a = (const unsigned char *)(&address->addr.in6.sin6_addr);
405 if (stringbuffersize >= 88)
407 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);
413 if (stringbuffersize >= 80)
415 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]);
424 int LHNETADDRESS_GetAddressType(const lhnetaddress_t *address)
427 return address->addresstype;
429 return LHNETADDRESSTYPE_NONE;
432 const char *LHNETADDRESS_GetInterfaceName(const lhnetaddress_t *vaddress)
434 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
436 if (address && address->addresstype == LHNETADDRESSTYPE_INET6)
440 static char ifname [IF_NAMESIZE];
442 if (if_indextoname(address->addr.in6.sin6_scope_id, ifname) == ifname)
447 // The Win32 API doesn't have if_indextoname() until Windows Vista,
448 // but luckily it just uses the interface ID as the interface name
450 static char ifname [16];
452 if (dpsnprintf(ifname, sizeof(ifname), "%lu", address->addr.in6.sin6_scope_id) > 0)
461 int LHNETADDRESS_GetPort(const lhnetaddress_t *address)
465 return address->port;
468 int LHNETADDRESS_SetPort(lhnetaddress_t *vaddress, int port)
470 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
473 address->port = port;
474 switch(address->addresstype)
476 case LHNETADDRESSTYPE_LOOP:
478 case LHNETADDRESSTYPE_INET4:
479 address->addr.in.sin_port = htons((unsigned short)port);
481 case LHNETADDRESSTYPE_INET6:
482 address->addr.in6.sin6_port = htons((unsigned short)port);
489 int LHNETADDRESS_Compare(const lhnetaddress_t *vaddress1, const lhnetaddress_t *vaddress2)
491 lhnetaddressnative_t *address1 = (lhnetaddressnative_t *)vaddress1;
492 lhnetaddressnative_t *address2 = (lhnetaddressnative_t *)vaddress2;
493 if (!address1 || !address2)
495 if (address1->addresstype != address2->addresstype)
497 switch(address1->addresstype)
499 case LHNETADDRESSTYPE_LOOP:
500 if (address1->port != address2->port)
503 case LHNETADDRESSTYPE_INET4:
504 if (address1->addr.in.sin_family != address2->addr.in.sin_family)
506 if (memcmp(&address1->addr.in.sin_addr, &address2->addr.in.sin_addr, sizeof(address1->addr.in.sin_addr)))
508 if (address1->port != address2->port)
511 case LHNETADDRESSTYPE_INET6:
512 if (address1->addr.in6.sin6_family != address2->addr.in6.sin6_family)
514 if (memcmp(&address1->addr.in6.sin6_addr, &address2->addr.in6.sin6_addr, sizeof(address1->addr.in6.sin6_addr)))
516 if (address1->port != address2->port)
524 typedef struct lhnetpacket_s
531 #ifndef STANDALONETEST
532 double sentdoubletime;
534 struct lhnetpacket_s *next, *prev;
538 static int lhnet_active;
539 static lhnetsocket_t lhnet_socketlist;
540 static lhnetpacket_t lhnet_packetlist;
542 static int lhnet_didWSAStartup = 0;
543 static WSADATA lhnet_winsockdata;
546 void LHNET_Init(void)
550 lhnet_socketlist.next = lhnet_socketlist.prev = &lhnet_socketlist;
551 lhnet_packetlist.next = lhnet_packetlist.prev = &lhnet_packetlist;
554 lhnet_didWSAStartup = !WSAStartup(MAKEWORD(1, 1), &lhnet_winsockdata);
555 if (!lhnet_didWSAStartup)
556 Con_Print("LHNET_Init: WSAStartup failed, networking disabled\n");
560 void LHNET_Shutdown(void)
565 while (lhnet_socketlist.next != &lhnet_socketlist)
566 LHNET_CloseSocket(lhnet_socketlist.next);
567 while (lhnet_packetlist.next != &lhnet_packetlist)
569 p = lhnet_packetlist.next;
570 p->prev->next = p->next;
571 p->next->prev = p->prev;
575 if (lhnet_didWSAStartup)
577 lhnet_didWSAStartup = 0;
584 static const char *LHNETPRIVATE_StrError(void)
587 int i = WSAGetLastError();
590 case WSAEINTR: return "WSAEINTR";
591 case WSAEBADF: return "WSAEBADF";
592 case WSAEACCES: return "WSAEACCES";
593 case WSAEFAULT: return "WSAEFAULT";
594 case WSAEINVAL: return "WSAEINVAL";
595 case WSAEMFILE: return "WSAEMFILE";
596 case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK";
597 case WSAEINPROGRESS: return "WSAEINPROGRESS";
598 case WSAEALREADY: return "WSAEALREADY";
599 case WSAENOTSOCK: return "WSAENOTSOCK";
600 case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ";
601 case WSAEMSGSIZE: return "WSAEMSGSIZE";
602 case WSAEPROTOTYPE: return "WSAEPROTOTYPE";
603 case WSAENOPROTOOPT: return "WSAENOPROTOOPT";
604 case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
605 case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
606 case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP";
607 case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT";
608 case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT";
609 case WSAEADDRINUSE: return "WSAEADDRINUSE";
610 case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL";
611 case WSAENETDOWN: return "WSAENETDOWN";
612 case WSAENETUNREACH: return "WSAENETUNREACH";
613 case WSAENETRESET: return "WSAENETRESET";
614 case WSAECONNABORTED: return "WSAECONNABORTED";
615 case WSAECONNRESET: return "WSAECONNRESET";
616 case WSAENOBUFS: return "WSAENOBUFS";
617 case WSAEISCONN: return "WSAEISCONN";
618 case WSAENOTCONN: return "WSAENOTCONN";
619 case WSAESHUTDOWN: return "WSAESHUTDOWN";
620 case WSAETOOMANYREFS: return "WSAETOOMANYREFS";
621 case WSAETIMEDOUT: return "WSAETIMEDOUT";
622 case WSAECONNREFUSED: return "WSAECONNREFUSED";
623 case WSAELOOP: return "WSAELOOP";
624 case WSAENAMETOOLONG: return "WSAENAMETOOLONG";
625 case WSAEHOSTDOWN: return "WSAEHOSTDOWN";
626 case WSAEHOSTUNREACH: return "WSAEHOSTUNREACH";
627 case WSAENOTEMPTY: return "WSAENOTEMPTY";
628 case WSAEPROCLIM: return "WSAEPROCLIM";
629 case WSAEUSERS: return "WSAEUSERS";
630 case WSAEDQUOT: return "WSAEDQUOT";
631 case WSAESTALE: return "WSAESTALE";
632 case WSAEREMOTE: return "WSAEREMOTE";
633 case WSAEDISCON: return "WSAEDISCON";
634 case 0: return "no error";
635 default: return "unknown WSAE error";
638 return strerror(errno);
642 void LHNET_SleepUntilPacket_Microseconds(int microseconds)
650 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
652 if (s->address.addresstype == LHNETADDRESSTYPE_INET4 || s->address.addresstype == LHNETADDRESSTYPE_INET6)
654 if (lastfd < s->inetsocket)
655 lastfd = s->inetsocket;
656 FD_SET((unsigned int)s->inetsocket, &fdreadset);
659 tv.tv_sec = microseconds / 1000000;
660 tv.tv_usec = microseconds % 1000000;
661 select(lastfd + 1, &fdreadset, NULL, NULL, &tv);
664 lhnetsocket_t *LHNET_OpenSocket_Connectionless(lhnetaddress_t *address)
666 lhnetsocket_t *lhnetsocket, *s;
669 lhnetsocket = (lhnetsocket_t *)Z_Malloc(sizeof(*lhnetsocket));
672 memset(lhnetsocket, 0, sizeof(*lhnetsocket));
673 lhnetsocket->address = *address;
674 switch(lhnetsocket->address.addresstype)
676 case LHNETADDRESSTYPE_LOOP:
677 if (lhnetsocket->address.port == 0)
679 // allocate a port dynamically
680 // this search will always terminate because there is never
681 // an allocated socket with port 0, so if the number wraps it
682 // will find the port is unused, and then refuse to use port
683 // 0, causing an intentional failure condition
684 lhnetsocket->address.port = 1024;
687 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
688 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
690 if (s == &lhnet_socketlist)
692 lhnetsocket->address.port++;
695 // check if the port is available
696 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
697 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.port == lhnetsocket->address.port)
699 if (s == &lhnet_socketlist && lhnetsocket->address.port != 0)
701 lhnetsocket->next = &lhnet_socketlist;
702 lhnetsocket->prev = lhnetsocket->next->prev;
703 lhnetsocket->next->prev = lhnetsocket;
704 lhnetsocket->prev->next = lhnetsocket;
708 case LHNETADDRESSTYPE_INET4:
709 case LHNETADDRESSTYPE_INET6:
711 if (lhnet_didWSAStartup)
714 if ((lhnetsocket->inetsocket = socket(address->addresstype == LHNETADDRESSTYPE_INET6 ? PF_INET6 : PF_INET, SOCK_DGRAM, IPPROTO_UDP)) != -1)
722 if (ioctlsocket(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
725 // We need to set this flag to tell the OS that we only listen on IPv6. If we don't
726 // most OSes will create a dual-protocol socket that also listens on IPv4. In this case
727 // if an IPv4 socket is already bound to the port we want, our bind() call will fail.
729 if (address->addresstype != LHNETADDRESSTYPE_INET6
730 || setsockopt (lhnetsocket->inetsocket, IPPROTO_IPV6, IPV6_V6ONLY,
731 (const char *)&ipv6_only, sizeof(ipv6_only)) == 0
733 // The Win32 API only supports IPV6_V6ONLY since Windows Vista, but fortunately
734 // the default value is what we want on Win32 anyway (IPV6_V6ONLY = true)
735 || SOCKETERRNO == WSAENOPROTOOPT
740 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
743 if (address->addresstype == LHNETADDRESSTYPE_INET6)
745 namelen = sizeof(localaddress->addr.in6);
746 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
747 if (bindresult != -1)
748 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
752 namelen = sizeof(localaddress->addr.in);
753 bindresult = bind(lhnetsocket->inetsocket, &localaddress->addr.sock, namelen);
754 if (bindresult != -1)
755 getsockname(lhnetsocket->inetsocket, &localaddress->addr.sock, &namelen);
757 if (bindresult != -1)
760 // enable broadcast on this socket
761 setsockopt(lhnetsocket->inetsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i));
762 lhnetsocket->next = &lhnet_socketlist;
763 lhnetsocket->prev = lhnetsocket->next->prev;
764 lhnetsocket->next->prev = lhnetsocket;
765 lhnetsocket->prev->next = lhnetsocket;
767 if (ioctlsocket(lhnetsocket->inetsocket, SIO_UDP_CONNRESET, &_false) == -1)
768 Con_DPrintf("LHNET_OpenSocket_Connectionless: ioctlsocket SIO_UDP_CONNRESET returned error: %s\n", LHNETPRIVATE_StrError());
773 Con_Printf("LHNET_OpenSocket_Connectionless: bind returned error: %s\n", LHNETPRIVATE_StrError());
777 Con_Printf("LHNET_OpenSocket_Connectionless: setsockopt(IPV6_V6ONLY) returned error: %s\n", LHNETPRIVATE_StrError());
781 Con_Printf("LHNET_OpenSocket_Connectionless: ioctlsocket returned error: %s\n", LHNETPRIVATE_StrError());
782 closesocket(lhnetsocket->inetsocket);
785 Con_Printf("LHNET_OpenSocket_Connectionless: socket returned error: %s\n", LHNETPRIVATE_StrError());
789 Con_Print("LHNET_OpenSocket_Connectionless: can't open a socket (WSAStartup failed during LHNET_Init)\n");
800 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
804 // unlink from socket list
805 if (lhnetsocket->next == NULL)
807 lhnetsocket->next->prev = lhnetsocket->prev;
808 lhnetsocket->prev->next = lhnetsocket->next;
809 lhnetsocket->next = NULL;
810 lhnetsocket->prev = NULL;
812 // no special close code for loopback, just inet
813 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
815 closesocket(lhnetsocket->inetsocket);
821 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
824 return &sock->address;
829 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *vaddress)
831 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
833 if (!lhnetsocket || !address || !content || maxcontentlength < 1)
835 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
838 lhnetpacket_t *p, *pnext;
839 // scan for any old packets to timeout while searching for a packet
840 // that is waiting to be delivered to this socket
841 currenttime = time(NULL);
842 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
845 if (p->timeout < currenttime)
848 p->next->prev = p->prev;
849 p->prev->next = p->next;
853 #ifndef STANDALONETEST
854 if (cl_netlocalping.value && (realtime - cl_netlocalping.value * (1.0 / 2000.0)) < p->sentdoubletime)
857 if (value == 0 && p->destinationport == lhnetsocket->address.port)
859 if (p->length <= maxcontentlength)
861 lhnetaddressnative_t *localaddress = (lhnetaddressnative_t *)&lhnetsocket->address;
862 *address = *localaddress;
863 address->port = p->sourceport;
864 memcpy(content, p->data, p->length);
870 p->next->prev = p->prev;
871 p->prev->next = p->next;
876 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
878 SOCKLEN_T inetaddresslength;
879 address->addresstype = LHNETADDRESSTYPE_NONE;
880 inetaddresslength = sizeof(address->addr.in);
881 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, 0, &address->addr.sock, &inetaddresslength);
884 address->addresstype = LHNETADDRESSTYPE_INET4;
885 address->port = ntohs(address->addr.in.sin_port);
888 else if (value == -1)
891 if (e == EWOULDBLOCK)
896 Con_Print("Connection refused\n");
899 Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
902 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
904 SOCKLEN_T inetaddresslength;
905 address->addresstype = LHNETADDRESSTYPE_NONE;
906 inetaddresslength = sizeof(address->addr.in6);
907 value = recvfrom(lhnetsocket->inetsocket, (char *)content, maxcontentlength, 0, &address->addr.sock, &inetaddresslength);
910 address->addresstype = LHNETADDRESSTYPE_INET6;
911 address->port = ntohs(address->addr.in6.sin6_port);
914 else if (value == -1)
917 if (e == EWOULDBLOCK)
922 Con_Print("Connection refused\n");
925 Con_Printf("LHNET_Read: recvfrom returned error: %s\n", LHNETPRIVATE_StrError());
931 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *vaddress)
933 lhnetaddressnative_t *address = (lhnetaddressnative_t *)vaddress;
935 if (!lhnetsocket || !address || !content || contentlength < 1)
937 if (lhnetsocket->address.addresstype != address->addresstype)
939 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
942 p = (lhnetpacket_t *)Z_Malloc(sizeof(*p) + contentlength);
943 p->data = (void *)(p + 1);
944 memcpy(p->data, content, contentlength);
945 p->length = contentlength;
946 p->sourceport = lhnetsocket->address.port;
947 p->destinationport = address->port;
948 p->timeout = time(NULL) + 10;
949 p->next = &lhnet_packetlist;
950 p->prev = p->next->prev;
953 #ifndef STANDALONETEST
954 p->sentdoubletime = realtime;
956 value = contentlength;
958 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
960 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, 0, (struct sockaddr *)&address->addr.in, sizeof(struct sockaddr_in));
963 if (SOCKETERRNO == EWOULDBLOCK)
965 Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
968 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
970 value = sendto(lhnetsocket->inetsocket, (char *)content, contentlength, 0, (struct sockaddr *)&address->addr.in6, sizeof(struct sockaddr_in6));
973 if (SOCKETERRNO == EWOULDBLOCK)
975 Con_Printf("LHNET_Write: sendto returned error: %s\n", LHNETPRIVATE_StrError());
981 #ifdef STANDALONETEST
982 int main(int argc, char **argv)
985 char *buffer = "test", buffer2[1024];
986 int blen = strlen(buffer);
988 lhnetsocket_t *sock1;
989 lhnetsocket_t *sock2;
990 lhnetaddress_t myaddy1;
991 lhnetaddress_t myaddy2;
992 lhnetaddress_t myaddy3;
993 lhnetaddress_t localhostaddy1;
994 lhnetaddress_t localhostaddy2;
998 printf("calling LHNET_Init\n");
1001 printf("calling LHNET_FromPort twice to create two local addresses\n");
1002 LHNETADDRESS_FromPort(&myaddy1, LHNETADDRESSTYPE_INET4, 4000);
1003 LHNETADDRESS_FromPort(&myaddy2, LHNETADDRESSTYPE_INET4, 4001);
1004 LHNETADDRESS_FromString(&localhostaddy1, "127.0.0.1", 4000);
1005 LHNETADDRESS_FromString(&localhostaddy2, "127.0.0.1", 4001);
1007 printf("calling LHNET_OpenSocket_Connectionless twice to create two local sockets\n");
1008 sock1 = LHNET_OpenSocket_Connectionless(&myaddy1);
1009 sock2 = LHNET_OpenSocket_Connectionless(&myaddy2);
1011 printf("calling LHNET_Write to send a packet from the first socket to the second socket\n");
1012 test1 = LHNET_Write(sock1, buffer, blen, &localhostaddy2);
1013 printf("sleeping briefly\n");
1019 printf("calling LHNET_Read on the second socket to read the packet sent from the first socket\n");
1020 test2 = LHNET_Read(sock2, buffer2, b2len - 1, &myaddy3);
1022 Con_Printf("socket to socket test succeeded\n");
1024 Con_Printf("socket to socket test failed\n");
1027 printf("press any key to exit\n");
1031 printf("calling LHNET_Shutdown\n");
1033 printf("exiting\n");
1036 lhnetsocket_t *sock[16], *sendsock;
1045 int sendmessagelength;
1046 lhnetaddress_t destaddress;
1047 lhnetaddress_t receiveaddress;
1048 lhnetaddress_t sockaddress[16];
1049 char buffer[1536], addressstring[128], addressstring2[128];
1050 if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
1052 printf("calling LHNET_Init()\n");
1056 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
1057 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
1058 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
1062 sendmessagelength = 0;
1064 for (i = 0;i < numsockets;i++)
1066 LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
1067 printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
1068 if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
1070 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1071 printf("opened socket successfully (address \"%s\")\n", addressstring2);
1075 printf("failed to open socket\n");
1086 count = atoi(argv[2]);
1087 if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
1089 sendmessage = argv[4];
1090 sendmessagelength = strlen(sendmessage);
1092 for (i = 0;i < numsockets;i++)
1093 if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
1095 if (sendsock == NULL)
1097 printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
1103 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
1107 printf("started, now listening for \"exit\" on the opened sockets\n");
1108 oldtime = time(NULL);
1116 for (i = 0;i < numsockets;i++)
1120 length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
1122 printf("localsock read error: length < 0");
1123 else if (length > 0 && length < (int)sizeof(buffer))
1126 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
1127 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1128 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
1129 if (!strcmp(buffer, "exit"))
1136 if (argc == 5 && count > 0)
1138 newtime = time(NULL);
1139 if (newtime != oldtime)
1141 LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
1142 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
1143 printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
1144 length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
1145 if (length == sendmessagelength)
1146 printf("sent successfully\n");
1148 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
1152 printf("Done sending, still listening for \"exit\"\n");
1156 for (i = 0;i < numsockets;i++)
1160 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
1161 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
1162 LHNET_CloseSocket(sock[i]);
1165 printf("calling LHNET_Shutdown()\n");
1169 printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");