2 // Written by Forest Hale 2003-06-15 and placed into public domain.
12 //#include <netinet/in.h>
13 //#include <arpa/inet.h>
15 #include <sys/socket.h>
16 #include <sys/ioctl.h>
20 // for Z_Malloc/Z_Free in quake
21 #ifndef STANDALONETEST
27 #define Z_Malloc malloc
33 int LHNETADDRESS_FromPort(lhnetaddress_t *address, int addresstype, int port)
39 case LHNETADDRESSTYPE_LOOP:
40 // local:port (loopback)
41 memset(address, 0, sizeof(*address));
42 address->addresstype = LHNETADDRESSTYPE_LOOP;
43 address->addressdata.loop.port = port;
45 case LHNETADDRESSTYPE_INET4:
46 // 0.0.0.0:port (INADDR_ANY, binds to all interfaces)
47 memset(address, 0, sizeof(*address));
48 address->addresstype = LHNETADDRESSTYPE_INET4;
49 address->addressdata.inet4.family = LHNETADDRESSTYPE_INET4_FAMILY;
50 address->addressdata.inet4.port = htons((unsigned short)port);
52 case LHNETADDRESSTYPE_INET6:
53 // [0:0:0:0:0:0:0:0]:port (IN6ADDR_ANY, binds to all interfaces)
54 memset(address, 0, sizeof(*address));
55 address->addresstype = LHNETADDRESSTYPE_INET6;
56 address->addressdata.inet6.family = LHNETADDRESSTYPE_INET6_FAMILY;
57 address->addressdata.inet6.port = htons((unsigned short)port);
63 int LHNETADDRESS_FromString(lhnetaddress_t *address, const char *string, int defaultport)
65 int port, namelen, d1, d2, d3, d4;
66 struct hostent *hostentry;
69 if (!address || !string)
71 memset(address, 0, sizeof(*address));
72 address->addresstype = LHNETADDRESSTYPE_NONE;
74 colon = strrchr(string, ':');
76 port = atoi(colon + 1);
78 colon = string + strlen(string);
81 namelen = colon - string;
84 if (string[0] == '[' && namelen > 0 && string[namelen-1] == ']') // ipv6
89 memcpy(name, string, namelen);
92 if (!strcmp(name, "local"))
94 address->addresstype = LHNETADDRESSTYPE_LOOP;
95 address->addressdata.loop.port = port;
98 // try to parse with gethostbyname first, because it can handle ipv4 and
99 // ipv6 (in various address formats), as well as dns names
100 hostentry = gethostbyname(name);
103 if (hostentry->h_addrtype == LHNETADDRESSTYPE_INET6_FAMILY)
106 address->addresstype = LHNETADDRESSTYPE_INET6;
107 address->addressdata.inet6.family = hostentry->h_addrtype;
108 address->addressdata.inet6.port = htons((unsigned short)port);
109 memcpy(address->addressdata.inet6.address, hostentry->h_addr_list[0], sizeof(address->addressdata.inet6.address));
110 #ifdef STANDALONETEST
111 printf("gethostbyname(\"%s\") returned ipv6 address [%x:%x:%x:%x:%x:%x:%x:%x]:%d\n", name, (int)address->addressdata.inet6.address[0], (int)address->addressdata.inet6.address[1], (int)address->addressdata.inet6.address[2], (int)address->addressdata.inet6.address[3], (int)address->addressdata.inet6.address[4], (int)address->addressdata.inet6.address[5], (int)address->addressdata.inet6.address[6], (int)address->addressdata.inet6.address[7], (int)ntohs(address->addressdata.inet6.port));
115 else if (hostentry->h_addrtype == LHNETADDRESSTYPE_INET4_FAMILY)
118 address->addresstype = LHNETADDRESSTYPE_INET4;
119 address->addressdata.inet4.family = hostentry->h_addrtype;
120 address->addressdata.inet4.port = htons((unsigned short)port);
121 memcpy(address->addressdata.inet4.address, hostentry->h_addr_list[0], sizeof(address->addressdata.inet4.address));
122 #ifdef STANDALONETEST
123 printf("gethostbyname(\"%s\") returned ipv4 address %d.%d.%d.%d:%d\n", name, (int)address->addressdata.inet4.address[0], (int)address->addressdata.inet4.address[1], (int)address->addressdata.inet4.address[2], (int)address->addressdata.inet4.address[3], (int)ntohs(address->addressdata.inet4.port));
128 // failed, try to parse as an ipv4 address as a fallback (is this needed?)
129 #ifdef STANDALONETEST
130 printf("gethostbyname and gethostbyaddr failed on address \"%s\"\n", name);
132 if (sscanf(name, "%d.%d.%d.%d", &d1, &d2, &d3, &d4) == 4 && (unsigned int)d1 < 256 && (unsigned int)d2 < 256 && (unsigned int)d3 < 256 && (unsigned int)d4 < 256)
134 // parsed a valid ipv4 address
135 address->addresstype = LHNETADDRESSTYPE_INET4;
136 address->addressdata.inet4.family = LHNETADDRESSTYPE_INET4_FAMILY;
137 address->addressdata.inet4.port = htons((unsigned short)port);
138 address->addressdata.inet4.address[0] = (unsigned char)d1;
139 address->addressdata.inet4.address[1] = (unsigned char)d2;
140 address->addressdata.inet4.address[2] = (unsigned char)d3;
141 address->addressdata.inet4.address[3] = (unsigned char)d4;
142 #ifdef STANDALONETEST
143 printf("manual parsing of ipv4 dotted decimal address \"%s\" successful: %d.%d.%d.%d:%d\n", string, (int)address->addressdata.inet4.address[0], (int)address->addressdata.inet4.address[1], (int)address->addressdata.inet4.address[2], (int)address->addressdata.inet4.address[3], (int)ntohs(address->addressdata.inet4.port));
150 int LHNETADDRESS_ToString(const lhnetaddress_t *address, char *string, int stringbuffersize, int includeport)
153 if (!address || !string || stringbuffersize < 1)
155 switch(address->addresstype)
159 case LHNETADDRESSTYPE_LOOP:
162 if (stringbuffersize >= 12)
164 sprintf(string, "local:%d", (int)address->addressdata.loop.port);
170 if (stringbuffersize >= 6)
172 strcpy(string, "local");
177 case LHNETADDRESSTYPE_INET4:
180 if (stringbuffersize >= 22)
182 sprintf(string, "%d.%d.%d.%d:%d", (int)address->addressdata.inet4.address[0], (int)address->addressdata.inet4.address[1], (int)address->addressdata.inet4.address[2], (int)address->addressdata.inet4.address[3], (int)ntohs(address->addressdata.inet4.port));
188 if (stringbuffersize >= 16)
190 sprintf(string, "%d.%d.%d.%d", (int)address->addressdata.inet4.address[0], (int)address->addressdata.inet4.address[1], (int)address->addressdata.inet4.address[2], (int)address->addressdata.inet4.address[3]);
195 case LHNETADDRESSTYPE_INET6:
198 if (stringbuffersize >= 88)
200 sprintf(string, "[%x:%x:%x:%x:%x:%x:%x:%x]:%d", (int)address->addressdata.inet6.address[0], (int)address->addressdata.inet6.address[1], (int)address->addressdata.inet6.address[2], (int)address->addressdata.inet6.address[3], (int)address->addressdata.inet6.address[4], (int)address->addressdata.inet6.address[5], (int)address->addressdata.inet6.address[6], (int)address->addressdata.inet6.address[7], (int)ntohs(address->addressdata.inet6.port));
206 if (stringbuffersize >= 80)
208 sprintf(string, "%x:%x:%x:%x:%x:%x:%x:%x", (int)address->addressdata.inet6.address[0], (int)address->addressdata.inet6.address[1], (int)address->addressdata.inet6.address[2], (int)address->addressdata.inet6.address[3], (int)address->addressdata.inet6.address[4], (int)address->addressdata.inet6.address[5], (int)address->addressdata.inet6.address[6], (int)address->addressdata.inet6.address[7]);
217 int LHNETADDRESS_GetAddressType(const lhnetaddress_t *address)
220 return address->addresstype;
222 return LHNETADDRESSTYPE_NONE;
225 int LHNETADDRESS_GetPort(const lhnetaddress_t *address)
229 switch(address->addresstype)
231 case LHNETADDRESSTYPE_LOOP:
232 return address->addressdata.loop.port;
233 case LHNETADDRESSTYPE_INET4:
234 return ntohs(address->addressdata.inet4.port);
235 case LHNETADDRESSTYPE_INET6:
236 return ntohs(address->addressdata.inet6.port);
242 int LHNETADDRESS_SetPort(lhnetaddress_t *address, int port)
246 switch(address->addresstype)
248 case LHNETADDRESSTYPE_LOOP:
249 address->addressdata.loop.port = port;
251 case LHNETADDRESSTYPE_INET4:
252 address->addressdata.inet4.port = htons((unsigned short)port);
254 case LHNETADDRESSTYPE_INET6:
255 address->addressdata.inet6.port = htons((unsigned short)port);
262 int LHNETADDRESS_Compare(const lhnetaddress_t *address1, const lhnetaddress_t *address2)
264 if (!address1 || !address2)
266 if (address1->addresstype != address2->addresstype)
268 switch(address1->addresstype)
270 case LHNETADDRESSTYPE_LOOP:
271 if (address1->addressdata.loop.port != address2->addressdata.loop.port)
274 case LHNETADDRESSTYPE_INET4:
275 if (address1->addressdata.inet4.family != address2->addressdata.inet4.family)
277 if (memcmp(address1->addressdata.inet4.address, address2->addressdata.inet4.address, sizeof(address1->addressdata.inet4.address)))
279 if (address1->addressdata.inet4.port != address2->addressdata.inet4.port)
282 case LHNETADDRESSTYPE_INET6:
283 if (address1->addressdata.inet6.family != address2->addressdata.inet6.family)
285 if (memcmp(address1->addressdata.inet6.address, address2->addressdata.inet6.address, sizeof(address1->addressdata.inet6.address)))
287 if (address1->addressdata.inet6.port != address2->addressdata.inet6.port)
295 typedef struct lhnetpacket_s
302 #ifndef STANDALONETEST
303 double sentdoubletime;
305 struct lhnetpacket_s *next, *prev;
309 static int lhnet_active;
310 static lhnetsocket_t lhnet_socketlist;
311 static lhnetpacket_t lhnet_packetlist;
313 static int lhnet_didWSAStartup = 0;
314 static WSADATA lhnet_winsockdata;
317 void LHNET_Init(void)
321 lhnet_socketlist.next = lhnet_socketlist.prev = &lhnet_socketlist;
322 lhnet_packetlist.next = lhnet_packetlist.prev = &lhnet_packetlist;
326 void LHNET_Shutdown(void)
331 while (lhnet_socketlist.next != &lhnet_socketlist)
332 LHNET_CloseSocket(lhnet_socketlist.next);
333 while (lhnet_packetlist.next != &lhnet_packetlist)
335 p = lhnet_packetlist.next;
336 p->prev->next = p->next;
337 p->next->prev = p->prev;
343 lhnetsocket_t *LHNET_OpenSocket_Connectionless(lhnetaddress_t *address)
345 lhnetsocket_t *lhnetsocket, *s;
348 lhnetsocket = Z_Malloc(sizeof(*lhnetsocket));
351 memset(lhnetsocket, 0, sizeof(*lhnetsocket));
352 lhnetsocket->address = *address;
353 switch(lhnetsocket->address.addresstype)
355 case LHNETADDRESSTYPE_LOOP:
356 if (lhnetsocket->address.addressdata.loop.port == 0)
358 // allocate a port dynamically
359 // this search will always terminate because there is never
360 // an allocated socket with port 0, so if the number wraps it
361 // will find the port is unused, and then refuse to use port
362 // 0, causing an intentional failure condition
363 lhnetsocket->address.addressdata.loop.port = 1024;
366 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
367 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.addressdata.loop.port == lhnetsocket->address.addressdata.loop.port)
369 if (s == &lhnet_socketlist)
371 lhnetsocket->address.addressdata.loop.port++;
374 // check if the port is available
375 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
376 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.addressdata.loop.port == lhnetsocket->address.addressdata.loop.port)
378 if (s == &lhnet_socketlist && lhnetsocket->address.addressdata.loop.port != 0)
380 lhnetsocket->next = &lhnet_socketlist;
381 lhnetsocket->prev = lhnetsocket->next->prev;
382 lhnetsocket->next->prev = lhnetsocket;
383 lhnetsocket->prev->next = lhnetsocket;
387 case LHNETADDRESSTYPE_INET4:
388 case LHNETADDRESSTYPE_INET6:
390 if (!lhnet_didWSAStartup && !WSAStartup(MAKEWORD(1, 1), &lhnet_winsockdata))
392 lhnet_didWSAStartup = 1;
396 if (address->addresstype == LHNETADDRESSTYPE_INET6)
397 lhnetsocket->inetsocket = socket(LHNETADDRESSTYPE_INET6_FAMILY, SOCK_DGRAM, IPPROTO_UDP);
399 lhnetsocket->inetsocket = socket(LHNETADDRESSTYPE_INET4_FAMILY, SOCK_DGRAM, IPPROTO_UDP);
400 if (lhnetsocket->inetsocket != -1)
404 if (ioctlsocket(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
407 if (ioctl(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
410 if (bind(lhnetsocket->inetsocket, (void *)&lhnetsocket->address.addressdata, address->addresstype == LHNETADDRESSTYPE_INET6 ? sizeof(lhnetsocket->address.addressdata.inet6) : sizeof(lhnetsocket->address.addressdata.inet4)) != -1)
412 lhnetsocket->next = &lhnet_socketlist;
413 lhnetsocket->prev = lhnetsocket->next->prev;
414 lhnetsocket->next->prev = lhnetsocket;
415 lhnetsocket->prev->next = lhnetsocket;
420 closesocket(lhnetsocket->inetsocket);
422 close(lhnetsocket->inetsocket);
435 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
439 // unlink from socket list
440 if (lhnetsocket->next == NULL)
442 lhnetsocket->next->prev = lhnetsocket->prev;
443 lhnetsocket->prev->next = lhnetsocket->next;
444 lhnetsocket->next = NULL;
445 lhnetsocket->prev = NULL;
447 // no special close code for loopback, just inet
448 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
451 closesocket(lhnetsocket->inetsocket);
453 close(lhnetsocket->inetsocket);
457 if (lhnet_socketlist.next == &lhnet_socketlist && lhnet_didWSAStartup)
459 lhnet_didWSAStartup = 0;
467 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
470 return &sock->address;
475 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *address)
478 if (!lhnetsocket || !address || !content || maxcontentlength < 1)
480 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
483 lhnetpacket_t *p, *pnext;
484 // scan for any old packets to timeout while searching for a packet
485 // that is waiting to be delivered to this socket
486 currenttime = time(NULL);
487 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
490 if (p->timeout < currenttime)
493 p->next->prev = p->prev;
494 p->prev->next = p->next;
498 #ifndef STANDALONETEST
499 if (p->sentdoubletime && Sys_DoubleTime() < p->sentdoubletime)
502 if (value == 0 && p->destinationport == lhnetsocket->address.addressdata.loop.port)
504 if (p->length <= maxcontentlength)
506 *address = lhnetsocket->address;
507 address->addressdata.loop.port = p->sourceport;
508 memcpy(content, p->data, p->length);
514 p->next->prev = p->prev;
515 p->prev->next = p->next;
520 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
522 int inetaddresslength;
523 address->addresstype = LHNETADDRESSTYPE_NONE;
524 inetaddresslength = sizeof(address->addressdata.inet4);
525 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, (struct sockaddr *)&address->addressdata.inet4, &inetaddresslength);
528 address->addresstype = LHNETADDRESSTYPE_INET4;
531 else if (value == -1)
534 int e = WSAGetLastError();
535 if (e == WSAEWOULDBLOCK)
539 case WSAECONNREFUSED:
540 Con_Printf("Connection refused\n");
544 if (errno == EWOULDBLOCK)
549 Con_Printf("Connection refused\n");
555 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
557 int inetaddresslength;
558 address->addresstype = LHNETADDRESSTYPE_NONE;
559 inetaddresslength = sizeof(address->addressdata.inet6);
560 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, (struct sockaddr *)&address->addressdata.inet6, &inetaddresslength);
563 address->addresstype = LHNETADDRESSTYPE_INET6;
566 else if (value == -1)
569 int e = WSAGetLastError();
570 if (e == WSAEWOULDBLOCK)
574 case WSAECONNREFUSED:
575 Con_Printf("Connection refused\n");
579 if (errno == EWOULDBLOCK)
584 Con_Printf("Connection refused\n");
593 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *address)
596 if (!lhnetsocket || !address || !content || contentlength < 1)
598 if (lhnetsocket->address.addresstype != address->addresstype)
600 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
603 p = Z_Malloc(sizeof(*p) + contentlength);
604 p->data = (void *)(p + 1);
605 memcpy(p->data, content, contentlength);
606 p->length = contentlength;
607 p->sourceport = lhnetsocket->address.addressdata.loop.port;
608 p->destinationport = address->addressdata.loop.port;
609 p->timeout = time(NULL) + 10;
610 p->next = &lhnet_packetlist;
611 p->prev = p->next->prev;
614 #ifndef STANDALONETEST
615 if (cl_fakelocalping_min.integer || cl_fakelocalping_max.integer)
616 p->sentdoubletime = Sys_DoubleTime() + (cl_fakelocalping_min.integer + ((cl_fakelocalping_max.integer - cl_fakelocalping_min.integer) * (rand() & 255) / 256)) / 1000.0;
618 value = contentlength;
620 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
622 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addressdata.inet4, sizeof(address->addressdata.inet4));
626 int e = WSAGetLastError();
627 if (e == WSAEWOULDBLOCK)
630 if (errno == EWOULDBLOCK)
635 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
637 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addressdata.inet6, sizeof(address->addressdata.inet6));
641 int e = WSAGetLastError();
642 if (e == WSAEWOULDBLOCK)
645 if (errno == EWOULDBLOCK)
653 #ifdef STANDALONETEST
654 int main(int argc, char **argv)
656 lhnetsocket_t *sock[16], *sendsock;
665 int sendmessagelength;
666 lhnetaddress_t destaddress;
667 lhnetaddress_t receiveaddress;
668 lhnetaddress_t sockaddress[16];
669 char buffer[1536], addressstring[128], addressstring2[128];
670 if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
672 printf("calling LHNET_Init()\n");
676 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
677 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
678 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
682 sendmessagelength = 0;
684 for (i = 0;i < numsockets;i++)
686 LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
687 printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
688 if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
690 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
691 printf("opened socket successfully (address \"%s\")\n", addressstring2);
695 printf("failed to open socket\n");
706 count = atoi(argv[2]);
707 if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
709 sendmessage = argv[4];
710 sendmessagelength = strlen(sendmessage);
712 for (i = 0;i < numsockets;i++)
713 if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
715 if (sendsock == NULL)
717 printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
723 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
727 printf("started, now listening for \"exit\" on the opened sockets\n");
728 oldtime = time(NULL);
736 for (i = 0;i < numsockets;i++)
740 length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
742 printf("localsock read error: length < 0");
743 else if (length > 0 && length < (int)sizeof(buffer))
746 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
747 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
748 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
749 if (!strcmp(buffer, "exit"))
756 if (argc == 5 && count > 0)
758 newtime = time(NULL);
759 if (newtime != oldtime)
761 LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
762 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
763 printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
764 length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
765 if (length == sendmessagelength)
766 printf("sent successfully\n");
768 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
772 printf("Done sending, still listening for \"exit\"\n");
776 for (i = 0;i < numsockets;i++)
780 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
781 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
782 LHNET_CloseSocket(sock[i]);
785 printf("calling LHNET_Shutdown()\n");
789 printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");