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
24 #define Z_Malloc malloc
30 int LHNETADDRESS_FromPort(lhnetaddress_t *address, int addresstype, int port)
36 case LHNETADDRESSTYPE_LOOP:
37 // local:port (loopback)
38 memset(address, 0, sizeof(*address));
39 address->addresstype = LHNETADDRESSTYPE_LOOP;
40 address->addressdata.loop.port = port;
42 case LHNETADDRESSTYPE_INET4:
43 // 0.0.0.0:port (INADDR_ANY, binds to all interfaces)
44 memset(address, 0, sizeof(*address));
45 address->addresstype = LHNETADDRESSTYPE_INET4;
46 address->addressdata.inet4.family = LHNETADDRESSTYPE_INET4_FAMILY;
47 address->addressdata.inet4.port = htons((unsigned short)port);
49 case LHNETADDRESSTYPE_INET6:
50 // [0:0:0:0:0:0:0:0]:port (IN6ADDR_ANY, binds to all interfaces)
51 memset(address, 0, sizeof(*address));
52 address->addresstype = LHNETADDRESSTYPE_INET6;
53 address->addressdata.inet6.family = LHNETADDRESSTYPE_INET6_FAMILY;
54 address->addressdata.inet6.port = htons((unsigned short)port);
60 int LHNETADDRESS_FromString(lhnetaddress_t *address, const char *string, int defaultport)
62 int port, namelen, d1, d2, d3, d4;
63 struct hostent *hostentry;
66 if (!address || !string)
68 memset(address, 0, sizeof(*address));
69 address->addresstype = LHNETADDRESSTYPE_NONE;
71 colon = strrchr(string, ':');
73 port = atoi(colon + 1);
75 colon = string + strlen(string);
78 namelen = colon - string;
81 if (string[0] == '[' && namelen > 0 && string[namelen-1] == ']') // ipv6
86 memcpy(name, string, namelen);
89 if (!strcmp(name, "local"))
91 address->addresstype = LHNETADDRESSTYPE_LOOP;
92 address->addressdata.loop.port = port;
95 // try to parse with gethostbyname first, because it can handle ipv4 and
96 // ipv6 (in various address formats), as well as dns names
97 hostentry = gethostbyname(name);
100 if (hostentry->h_addrtype == LHNETADDRESSTYPE_INET6_FAMILY)
103 address->addresstype = LHNETADDRESSTYPE_INET6;
104 address->addressdata.inet6.family = hostentry->h_addrtype;
105 address->addressdata.inet6.port = htons((unsigned short)port);
106 memcpy(address->addressdata.inet6.address, hostentry->h_addr_list[0], sizeof(address->addressdata.inet6.address));
107 #ifdef STANDALONETEST
108 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));
112 else if (hostentry->h_addrtype == LHNETADDRESSTYPE_INET4_FAMILY)
115 address->addresstype = LHNETADDRESSTYPE_INET4;
116 address->addressdata.inet4.family = hostentry->h_addrtype;
117 address->addressdata.inet4.port = htons((unsigned short)port);
118 memcpy(address->addressdata.inet4.address, hostentry->h_addr_list[0], sizeof(address->addressdata.inet4.address));
119 #ifdef STANDALONETEST
120 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));
125 // failed, try to parse as an ipv4 address as a fallback (is this needed?)
126 #ifdef STANDALONETEST
127 printf("gethostbyname and gethostbyaddr failed on address \"%s\"\n", name);
129 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)
131 // parsed a valid ipv4 address
132 address->addresstype = LHNETADDRESSTYPE_INET4;
133 address->addressdata.inet4.family = LHNETADDRESSTYPE_INET4_FAMILY;
134 address->addressdata.inet4.port = htons((unsigned short)port);
135 address->addressdata.inet4.address[0] = (unsigned char)d1;
136 address->addressdata.inet4.address[1] = (unsigned char)d2;
137 address->addressdata.inet4.address[2] = (unsigned char)d3;
138 address->addressdata.inet4.address[3] = (unsigned char)d4;
139 #ifdef STANDALONETEST
140 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));
147 int LHNETADDRESS_ToString(const lhnetaddress_t *address, char *string, int stringbuffersize, int includeport)
150 if (!address || !string || stringbuffersize < 1)
152 switch(address->addresstype)
156 case LHNETADDRESSTYPE_LOOP:
159 if (stringbuffersize >= 12)
161 sprintf(string, "local:%d", (int)address->addressdata.loop.port);
167 if (stringbuffersize >= 6)
169 strcpy(string, "local");
174 case LHNETADDRESSTYPE_INET4:
177 if (stringbuffersize >= 22)
179 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));
185 if (stringbuffersize >= 16)
187 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]);
192 case LHNETADDRESSTYPE_INET6:
195 if (stringbuffersize >= 88)
197 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));
203 if (stringbuffersize >= 80)
205 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]);
214 int LHNETADDRESS_GetAddressType(const lhnetaddress_t *address)
217 return address->addresstype;
219 return LHNETADDRESSTYPE_NONE;
222 int LHNETADDRESS_GetPort(const lhnetaddress_t *address)
226 switch(address->addresstype)
228 case LHNETADDRESSTYPE_LOOP:
229 return address->addressdata.loop.port;
230 case LHNETADDRESSTYPE_INET4:
231 return ntohs(address->addressdata.inet4.port);
232 case LHNETADDRESSTYPE_INET6:
233 return ntohs(address->addressdata.inet6.port);
239 int LHNETADDRESS_SetPort(lhnetaddress_t *address, int port)
243 switch(address->addresstype)
245 case LHNETADDRESSTYPE_LOOP:
246 address->addressdata.loop.port = port;
248 case LHNETADDRESSTYPE_INET4:
249 address->addressdata.inet4.port = htons((unsigned short)port);
251 case LHNETADDRESSTYPE_INET6:
252 address->addressdata.inet6.port = htons((unsigned short)port);
259 int LHNETADDRESS_Compare(const lhnetaddress_t *address1, const lhnetaddress_t *address2)
261 if (!address1 || !address2)
263 if (address1->addresstype != address2->addresstype)
265 switch(address1->addresstype)
267 case LHNETADDRESSTYPE_LOOP:
268 if (address1->addressdata.loop.port != address2->addressdata.loop.port)
271 case LHNETADDRESSTYPE_INET4:
272 if (address1->addressdata.inet4.family != address2->addressdata.inet4.family)
274 if (memcmp(address1->addressdata.inet4.address, address2->addressdata.inet4.address, sizeof(address1->addressdata.inet4.address)))
276 if (address1->addressdata.inet4.port != address2->addressdata.inet4.port)
279 case LHNETADDRESSTYPE_INET6:
280 if (address1->addressdata.inet6.family != address2->addressdata.inet6.family)
282 if (memcmp(address1->addressdata.inet6.address, address2->addressdata.inet6.address, sizeof(address1->addressdata.inet6.address)))
284 if (address1->addressdata.inet6.port != address2->addressdata.inet6.port)
292 typedef struct lhnetpacket_s
299 struct lhnetpacket_s *next, *prev;
303 static int lhnet_active;
304 static lhnetsocket_t lhnet_socketlist;
305 static lhnetpacket_t lhnet_packetlist;
307 static int lhnet_didWSAStartup = 0;
308 static WSADATA lhnet_winsockdata;
311 void LHNET_Init(void)
315 lhnet_socketlist.next = lhnet_socketlist.prev = &lhnet_socketlist;
316 lhnet_packetlist.next = lhnet_packetlist.prev = &lhnet_packetlist;
320 void LHNET_Shutdown(void)
325 while (lhnet_socketlist.next != &lhnet_socketlist)
326 LHNET_CloseSocket(lhnet_socketlist.next);
327 while (lhnet_packetlist.next != &lhnet_packetlist)
329 p = lhnet_packetlist.next;
330 p->prev->next = p->next;
331 p->next->prev = p->prev;
337 lhnetsocket_t *LHNET_OpenSocket_Connectionless(lhnetaddress_t *address)
339 lhnetsocket_t *lhnetsocket, *s;
342 lhnetsocket = Z_Malloc(sizeof(*lhnetsocket));
345 memset(lhnetsocket, 0, sizeof(*lhnetsocket));
346 lhnetsocket->address = *address;
347 switch(lhnetsocket->address.addresstype)
349 case LHNETADDRESSTYPE_LOOP:
350 if (lhnetsocket->address.addressdata.loop.port == 0)
352 // allocate a port dynamically
353 // this search will always terminate because there is never
354 // an allocated socket with port 0, so if the number wraps it
355 // will find the port is unused, and then refuse to use port
356 // 0, causing an intentional failure condition
357 lhnetsocket->address.addressdata.loop.port = 1024;
360 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
361 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.addressdata.loop.port == lhnetsocket->address.addressdata.loop.port)
363 if (s == &lhnet_socketlist)
365 lhnetsocket->address.addressdata.loop.port++;
368 // check if the port is available
369 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
370 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.addressdata.loop.port == lhnetsocket->address.addressdata.loop.port)
372 if (s == &lhnet_socketlist && lhnetsocket->address.addressdata.loop.port != 0)
374 lhnetsocket->next = &lhnet_socketlist;
375 lhnetsocket->prev = lhnetsocket->next->prev;
376 lhnetsocket->next->prev = lhnetsocket;
377 lhnetsocket->prev->next = lhnetsocket;
381 case LHNETADDRESSTYPE_INET4:
382 case LHNETADDRESSTYPE_INET6:
384 if (!lhnet_didWSAStartup && !WSAStartup(MAKEWORD(1, 1), &lhnet_winsockdata))
386 lhnet_didWSAStartup = 1;
390 if (address->addresstype == LHNETADDRESSTYPE_INET6)
391 lhnetsocket->inetsocket = socket(LHNETADDRESSTYPE_INET6_FAMILY, SOCK_DGRAM, IPPROTO_UDP);
393 lhnetsocket->inetsocket = socket(LHNETADDRESSTYPE_INET4_FAMILY, SOCK_DGRAM, IPPROTO_UDP);
394 if (lhnetsocket->inetsocket != -1)
398 if (ioctlsocket(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
401 if (ioctl(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
404 if (bind(lhnetsocket->inetsocket, (void *)&lhnetsocket->address.addressdata, address->addresstype == LHNETADDRESSTYPE_INET6 ? sizeof(lhnetsocket->address.addressdata.inet6) : sizeof(lhnetsocket->address.addressdata.inet4)) != -1)
406 lhnetsocket->next = &lhnet_socketlist;
407 lhnetsocket->prev = lhnetsocket->next->prev;
408 lhnetsocket->next->prev = lhnetsocket;
409 lhnetsocket->prev->next = lhnetsocket;
414 closesocket(lhnetsocket->inetsocket);
416 close(lhnetsocket->inetsocket);
429 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
433 // unlink from socket list
434 if (lhnetsocket->next == NULL)
436 lhnetsocket->next->prev = lhnetsocket->prev;
437 lhnetsocket->prev->next = lhnetsocket->next;
438 lhnetsocket->next = NULL;
439 lhnetsocket->prev = NULL;
441 // no special close code for loopback, just inet
442 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
445 closesocket(lhnetsocket->inetsocket);
447 close(lhnetsocket->inetsocket);
451 if (lhnet_socketlist.next == &lhnet_socketlist && lhnet_didWSAStartup)
453 lhnet_didWSAStartup = 0;
461 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
464 return &sock->address;
469 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *address)
472 if (!lhnetsocket || !address || !content || maxcontentlength < 1)
474 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
477 lhnetpacket_t *p, *pnext;
478 // scan for any old packets to timeout while searching for a packet
479 // that is waiting to be delivered to this socket
480 currenttime = time(NULL);
481 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
484 if (value == 0 && p->destinationport == lhnetsocket->address.addressdata.loop.port)
486 if (p->length <= maxcontentlength)
488 *address = lhnetsocket->address;
489 address->addressdata.loop.port = p->sourceport;
490 memcpy(content, p->data, p->length);
496 p->next->prev = p->prev;
497 p->prev->next = p->next;
500 else if (p->timeout < currenttime)
503 p->next->prev = p->prev;
504 p->prev->next = p->next;
509 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
511 int inetaddresslength;
512 address->addresstype = LHNETADDRESSTYPE_NONE;
513 inetaddresslength = sizeof(address->addressdata.inet4);
514 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, (struct sockaddr *)&address->addressdata.inet4, &inetaddresslength);
517 address->addresstype = LHNETADDRESSTYPE_INET4;
520 else if (value == -1)
523 int e = WSAGetLastError();
524 if (e == WSAEWOULDBLOCK || e == WSAECONNREFUSED)
527 if (errno == EWOULDBLOCK || errno == ECONNREFUSED)
532 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
534 int inetaddresslength;
535 address->addresstype = LHNETADDRESSTYPE_NONE;
536 inetaddresslength = sizeof(address->addressdata.inet6);
537 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, (struct sockaddr *)&address->addressdata.inet6, &inetaddresslength);
540 address->addresstype = LHNETADDRESSTYPE_INET6;
543 else if (value == -1)
546 int e = WSAGetLastError();
547 if (e == WSAEWOULDBLOCK || e == WSAECONNREFUSED)
550 if (errno == EWOULDBLOCK || errno == ECONNREFUSED)
558 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *address)
561 if (!lhnetsocket || !address || !content || contentlength < 1)
563 if (lhnetsocket->address.addresstype != address->addresstype)
565 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
568 p = Z_Malloc(sizeof(*p) + contentlength);
569 p->data = (void *)(p + 1);
570 memcpy(p->data, content, contentlength);
571 p->length = contentlength;
572 p->sourceport = lhnetsocket->address.addressdata.loop.port;
573 p->destinationport = address->addressdata.loop.port;
574 p->timeout = time(NULL) + 10;
575 p->next = &lhnet_packetlist;
576 p->prev = p->next->prev;
579 value = contentlength;
581 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
583 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addressdata.inet4, sizeof(address->addressdata.inet4));
587 int e = WSAGetLastError();
588 if (e == WSAEWOULDBLOCK)
591 if (errno == EWOULDBLOCK)
596 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
598 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addressdata.inet6, sizeof(address->addressdata.inet6));
602 int e = WSAGetLastError();
603 if (e == WSAEWOULDBLOCK)
606 if (errno == EWOULDBLOCK)
614 #ifdef STANDALONETEST
615 int main(int argc, char **argv)
617 lhnetsocket_t *sock[16], *sendsock;
626 int sendmessagelength;
627 lhnetaddress_t destaddress;
628 lhnetaddress_t receiveaddress;
629 lhnetaddress_t sockaddress[16];
630 char buffer[1536], addressstring[128], addressstring2[128];
631 if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
633 printf("calling LHNET_Init()\n");
637 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
638 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
639 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
643 sendmessagelength = 0;
645 for (i = 0;i < numsockets;i++)
647 LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
648 printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
649 if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
651 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
652 printf("opened socket successfully (address \"%s\")\n", addressstring2);
656 printf("failed to open socket\n");
667 count = atoi(argv[2]);
668 if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
670 sendmessage = argv[4];
671 sendmessagelength = strlen(sendmessage);
673 for (i = 0;i < numsockets;i++)
674 if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
676 if (sendsock == NULL)
678 printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
684 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
688 printf("started, now listening for \"exit\" on the opened sockets\n");
689 oldtime = time(NULL);
697 for (i = 0;i < numsockets;i++)
701 length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
703 printf("localsock read error: length < 0");
704 else if (length > 0 && length < (int)sizeof(buffer))
707 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
708 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
709 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
710 if (!strcmp(buffer, "exit"))
717 if (argc == 5 && count > 0)
719 newtime = time(NULL);
720 if (newtime != oldtime)
722 LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
723 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
724 printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
725 length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
726 if (length == sendmessagelength)
727 printf("sent successfully\n");
729 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
733 printf("Done sending, still listening for \"exit\"\n");
737 for (i = 0;i < numsockets;i++)
741 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
742 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
743 LHNET_CloseSocket(sock[i]);
746 printf("calling LHNET_Shutdown()\n");
750 printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");