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
24 #define Z_Malloc malloc
30 int LHNETADDRESS_FromPort(lhnetaddress_t *address, int addresstype, int port)
34 case LHNETADDRESSTYPE_LOOP:
35 // local:port (loopback)
36 memset(address, 0, sizeof(*address));
37 address->addresstype = LHNETADDRESSTYPE_LOOP;
38 address->addressdata.loop.port = port;
40 case LHNETADDRESSTYPE_INET4:
41 // 0.0.0.0:port (INADDR_ANY, binds to all interfaces)
42 memset(address, 0, sizeof(*address));
43 address->addresstype = LHNETADDRESSTYPE_INET4;
44 address->addressdata.inet4.family = LHNETADDRESSTYPE_INET4_FAMILY;
45 address->addressdata.inet4.port = htons(port);
47 case LHNETADDRESSTYPE_INET6:
48 // [0:0:0:0:0:0:0:0]:port (IN6ADDR_ANY, binds to all interfaces)
49 memset(address, 0, sizeof(*address));
50 address->addresstype = LHNETADDRESSTYPE_INET6;
51 address->addressdata.inet6.family = LHNETADDRESSTYPE_INET6_FAMILY;
52 address->addressdata.inet6.port = htons(port);
58 int LHNETADDRESS_FromString(lhnetaddress_t *address, const char *string, int defaultport)
60 int i, port, namelen, number;
61 struct hostent *hostentry;
64 memset(address, 0, sizeof(*address));
65 address->addresstype = LHNETADDRESSTYPE_NONE;
67 colon = strrchr(string, ':');
69 port = atoi(colon + 1);
71 colon = string + strlen(string);
74 namelen = colon - string;
77 if (string[0] == '[' && namelen > 0 && string[namelen-1] == ']') // ipv6
82 memcpy(name, string, namelen);
85 if (!strcmp(name, "local"))
87 address->addresstype = LHNETADDRESSTYPE_LOOP;
88 address->addressdata.loop.port = port;
91 // try to parse with gethostbyname first, because it can handle ipv4 and
92 // ipv6 (in various address formats), as well as dns names
96 hostentry = gethostbyaddr(name, namelen, LHNETADDRESSTYPE_INET6_FAMILY);
98 hostentry = gethostbyaddr(name, namelen, LHNETADDRESSTYPE_INET4_FAMILY);
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(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(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));
129 // failed, try to parse as an ipv4 address as a fallback (is this needed?)
130 #ifdef STANDALONETEST
131 printf("gethostbyname and gethostbyaddr failed on address \"%s\"\n", name);
133 for (i = 0, number = 0;i < 4;string++)
135 if (*string >= '0' && *string <= '9')
136 number = number * 10 + (*string - '0');
137 else if (number < 256 && (*string == '.' || *string == ':'))
139 address->addressdata.inet4.address[i++] = number;
144 if (*string == 0 || *string == ':')
149 // parsed a valid ipv4 address
150 address->addresstype = LHNETADDRESSTYPE_INET4;
151 address->addressdata.inet4.family = LHNETADDRESSTYPE_INET4_FAMILY;
152 address->addressdata.inet4.port = htons(port);
153 #ifdef STANDALONETEST
154 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));
161 int LHNETADDRESS_ToString(const lhnetaddress_t *address, char *string, int stringbuffersize, int includeport)
164 switch(address->addresstype)
168 case LHNETADDRESSTYPE_LOOP:
171 if (stringbuffersize >= 12)
173 sprintf(string, "local:%d", (int)address->addressdata.loop.port);
179 if (stringbuffersize >= 6)
181 strcpy(string, "local");
186 case LHNETADDRESSTYPE_INET4:
189 if (stringbuffersize >= 22)
191 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));
197 if (stringbuffersize >= 16)
199 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]);
204 case LHNETADDRESSTYPE_INET6:
207 if (stringbuffersize >= 88)
209 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));
215 if (stringbuffersize >= 80)
217 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]);
226 int LHNETADDRESS_GetAddressType(const lhnetaddress_t *address)
228 return address->addresstype;
231 int LHNETADDRESS_GetPort(const lhnetaddress_t *address)
233 switch(address->addresstype)
235 case LHNETADDRESSTYPE_LOOP:
236 return address->addressdata.loop.port;
237 case LHNETADDRESSTYPE_INET4:
238 return ntohs(address->addressdata.inet4.port);
239 case LHNETADDRESSTYPE_INET6:
240 return ntohs(address->addressdata.inet6.port);
246 int LHNETADDRESS_SetPort(lhnetaddress_t *address, int port)
248 switch(address->addresstype)
250 case LHNETADDRESSTYPE_LOOP:
251 address->addressdata.loop.port = port;
253 case LHNETADDRESSTYPE_INET4:
254 address->addressdata.inet4.port = htons(port);
256 case LHNETADDRESSTYPE_INET6:
257 address->addressdata.inet6.port = htons(port);
264 int LHNETADDRESS_Compare(const lhnetaddress_t *address1, const lhnetaddress_t *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 struct lhnetpacket_s *next, *prev;
306 static int lhnet_active;
307 static lhnetsocket_t lhnet_socketlist;
308 static lhnetpacket_t lhnet_packetlist;
310 static int lhnet_didWSAStartup = 0;
311 static WSADATA lhnet_winsockdata;
314 void LHNET_Init(void)
318 lhnet_socketlist.next = lhnet_socketlist.prev = &lhnet_socketlist;
319 lhnet_packetlist.next = lhnet_packetlist.prev = &lhnet_packetlist;
323 void LHNET_Shutdown(void)
328 while (lhnet_socketlist.next != &lhnet_socketlist)
329 LHNET_CloseSocket(lhnet_socketlist.next);
330 while (lhnet_packetlist.next != &lhnet_packetlist)
332 p = lhnet_packetlist.next;
333 p->prev->next = p->next;
334 p->next->prev = p->prev;
340 lhnetsocket_t *LHNET_OpenSocket_Connectionless(lhnetaddress_t *address)
342 lhnetsocket_t *lhnetsocket, *s;
343 lhnetsocket = Z_Malloc(sizeof(*lhnetsocket));
346 memset(lhnetsocket, 0, sizeof(*lhnetsocket));
347 lhnetsocket->address = *address;
348 switch(lhnetsocket->address.addresstype)
350 case LHNETADDRESSTYPE_LOOP:
351 if (lhnetsocket->address.addressdata.loop.port == 0)
353 // allocate a port dynamically
354 // this search will always terminate because there is never
355 // an allocated socket with port 0, so if the number wraps it
356 // will find the port is unused, and then refuse to use port
357 // 0, causing an intentional failure condition
358 lhnetsocket->address.addressdata.loop.port = 1024;
361 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
362 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.addressdata.loop.port == lhnetsocket->address.addressdata.loop.port)
364 if (s == &lhnet_socketlist)
366 lhnetsocket->address.addressdata.loop.port++;
369 // check if the port is available
370 for (s = lhnet_socketlist.next;s != &lhnet_socketlist;s = s->next)
371 if (s->address.addresstype == lhnetsocket->address.addresstype && s->address.addressdata.loop.port == lhnetsocket->address.addressdata.loop.port)
373 if (s == &lhnet_socketlist && lhnetsocket->address.addressdata.loop.port != 0)
375 lhnetsocket->next = &lhnet_socketlist;
376 lhnetsocket->prev = lhnetsocket->next->prev;
377 lhnetsocket->next->prev = lhnetsocket;
378 lhnetsocket->prev->next = lhnetsocket;
382 case LHNETADDRESSTYPE_INET4:
383 case LHNETADDRESSTYPE_INET6:
385 if (!lhnet_didWSAStartup && !WSAStartup(MAKEWORD(1, 1), &lhnet_winsockdata))
387 lhnet_didWSAStartup = 1;
391 if (address->addresstype == LHNETADDRESSTYPE_INET6)
392 lhnetsocket->inetsocket = socket(LHNETADDRESSTYPE_INET6_FAMILY, SOCK_DGRAM, IPPROTO_UDP);
394 lhnetsocket->inetsocket = socket(LHNETADDRESSTYPE_INET4_FAMILY, SOCK_DGRAM, IPPROTO_UDP);
395 if (lhnetsocket->inetsocket != -1)
399 if (ioctlsocket(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
402 if (ioctl(lhnetsocket->inetsocket, FIONBIO, &_true) != -1)
405 if (bind(lhnetsocket->inetsocket, (void *)&lhnetsocket->address.addressdata, address->addresstype == LHNETADDRESSTYPE_INET6 ? sizeof(lhnetsocket->address.addressdata.inet6) : sizeof(lhnetsocket->address.addressdata.inet4)) != -1)
407 lhnetsocket->next = &lhnet_socketlist;
408 lhnetsocket->prev = lhnetsocket->next->prev;
409 lhnetsocket->next->prev = lhnetsocket;
410 lhnetsocket->prev->next = lhnetsocket;
415 closesocket(lhnetsocket->inetsocket);
417 close(lhnetsocket->inetsocket);
430 void LHNET_CloseSocket(lhnetsocket_t *lhnetsocket)
434 // unlink from socket list
435 if (lhnetsocket->next == NULL)
437 lhnetsocket->next->prev = lhnetsocket->prev;
438 lhnetsocket->prev->next = lhnetsocket->next;
439 lhnetsocket->next = NULL;
440 lhnetsocket->prev = NULL;
442 // no special close code for loopback, just inet
443 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4 || lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
446 closesocket(lhnetsocket->inetsocket);
448 close(lhnetsocket->inetsocket);
452 if (lhnet_socketlist.next == &lhnet_socketlist && lhnet_didWSAStartup)
454 lhnet_didWSAStartup = 0;
462 lhnetaddress_t *LHNET_AddressFromSocket(lhnetsocket_t *sock)
464 return &sock->address;
467 int LHNET_Read(lhnetsocket_t *lhnetsocket, void *content, int maxcontentlength, lhnetaddress_t *address)
470 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
473 lhnetpacket_t *p, *pnext;
474 // scan for any old packets to timeout while searching for a packet
475 // that is waiting to be delivered to this socket
476 currenttime = time(NULL);
477 for (p = lhnet_packetlist.next;p != &lhnet_packetlist;p = pnext)
480 if (value == 0 && p->destinationport == lhnetsocket->address.addressdata.loop.port)
482 if (p->length <= maxcontentlength)
484 *address = lhnetsocket->address;
485 address->addressdata.loop.port = p->sourceport;
486 memcpy(content, p->data, p->length);
492 p->next->prev = p->prev;
493 p->prev->next = p->next;
496 else if (p->timeout < currenttime)
499 p->next->prev = p->prev;
500 p->prev->next = p->next;
505 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
507 int inetaddresslength;
508 address->addresstype = LHNETADDRESSTYPE_NONE;
509 inetaddresslength = sizeof(address->addressdata.inet4);
510 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, (struct sockaddr *)&address->addressdata.inet4, &inetaddresslength);
513 address->addresstype = LHNETADDRESSTYPE_INET4;
516 else if (value == -1)
519 int e = WSAGetLastError();
520 if (e == WSAEWOULDBLOCK || e == WSAECONNREFUSED)
523 if (errno == EWOULDBLOCK || errno == ECONNREFUSED)
528 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
530 int inetaddresslength;
531 address->addresstype = LHNETADDRESSTYPE_NONE;
532 inetaddresslength = sizeof(address->addressdata.inet6);
533 value = recvfrom(lhnetsocket->inetsocket, content, maxcontentlength, 0, (struct sockaddr *)&address->addressdata.inet6, &inetaddresslength);
536 address->addresstype = LHNETADDRESSTYPE_INET6;
539 else if (value == -1)
542 int e = WSAGetLastError();
543 if (e == WSAEWOULDBLOCK || e == WSAECONNREFUSED)
546 if (errno == EWOULDBLOCK || errno == ECONNREFUSED)
554 int LHNET_Write(lhnetsocket_t *lhnetsocket, const void *content, int contentlength, const lhnetaddress_t *address)
557 if (lhnetsocket->address.addresstype != address->addresstype)
559 if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_LOOP)
562 p = Z_Malloc(sizeof(*p) + contentlength);
563 p->data = (void *)(p + 1);
564 memcpy(p->data, content, contentlength);
565 p->length = contentlength;
566 p->sourceport = lhnetsocket->address.addressdata.loop.port;
567 p->destinationport = address->addressdata.loop.port;
568 p->timeout = time(NULL) + 10;
569 p->next = &lhnet_packetlist;
570 p->prev = p->next->prev;
573 value = contentlength;
575 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET4)
577 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addressdata.inet4, sizeof(address->addressdata.inet4));
581 int e = WSAGetLastError();
582 if (e == WSAEWOULDBLOCK)
585 if (errno == EWOULDBLOCK)
590 else if (lhnetsocket->address.addresstype == LHNETADDRESSTYPE_INET6)
592 value = sendto(lhnetsocket->inetsocket, content, contentlength, 0, (struct sockaddr *)&address->addressdata.inet6, sizeof(address->addressdata.inet6));
596 int e = WSAGetLastError();
597 if (e == WSAEWOULDBLOCK)
600 if (errno == EWOULDBLOCK)
608 #ifdef STANDALONETEST
609 int main(int argc, char **argv)
611 lhnetsocket_t *sock[16], *sendsock;
620 int sendmessagelength;
621 lhnetaddress_t destaddress;
622 lhnetaddress_t receiveaddress;
623 lhnetaddress_t sockaddress[16];
624 char buffer[1536], addressstring[128], addressstring2[128];
625 if ((argc == 2 || argc == 5) && (port = atoi(argv[1])) >= 1 && port < 65535)
627 printf("calling LHNET_Init()\n");
631 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_LOOP, port);
632 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET4, port);
633 LHNETADDRESS_FromPort(&sockaddress[numsockets++], LHNETADDRESSTYPE_INET6, port+1);
637 sendmessagelength = 0;
639 for (i = 0;i < numsockets;i++)
641 LHNETADDRESS_ToString(&sockaddress[i], addressstring, sizeof(addressstring), 1);
642 printf("calling LHNET_OpenSocket_Connectionless(<%s>)\n", addressstring);
643 if ((sock[i] = LHNET_OpenSocket_Connectionless(&sockaddress[i])))
645 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
646 printf("opened socket successfully (address \"%s\")\n", addressstring2);
650 printf("failed to open socket\n");
661 count = atoi(argv[2]);
662 if (LHNETADDRESS_FromString(&destaddress, argv[3], -1))
664 sendmessage = argv[4];
665 sendmessagelength = strlen(sendmessage);
667 for (i = 0;i < numsockets;i++)
668 if (sock[i] && LHNETADDRESS_GetAddressType(&destaddress) == LHNETADDRESS_GetAddressType(&sockaddress[i]))
670 if (sendsock == NULL)
672 printf("Could not find an open socket matching the addresstype (%i) of destination address, switching to listen only mode\n", LHNETADDRESS_GetAddressType(&destaddress));
678 printf("LHNETADDRESS_FromString did not like the address \"%s\", switching to listen only mode\n", argv[3]);
682 printf("started, now listening for \"exit\" on the opened sockets\n");
683 oldtime = time(NULL);
691 for (i = 0;i < numsockets;i++)
695 length = LHNET_Read(sock[i], buffer, sizeof(buffer), &receiveaddress);
697 printf("localsock read error: length < 0");
698 else if (length > 0 && length < (int)sizeof(buffer))
701 LHNETADDRESS_ToString(&receiveaddress, addressstring, sizeof(addressstring), 1);
702 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
703 printf("received message \"%s\" from \"%s\" on socket \"%s\"\n", buffer, addressstring, addressstring2);
704 if (!strcmp(buffer, "exit"))
711 if (argc == 5 && count > 0)
713 newtime = time(NULL);
714 if (newtime != oldtime)
716 LHNETADDRESS_ToString(&destaddress, addressstring, sizeof(addressstring), 1);
717 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sendsock), addressstring2, sizeof(addressstring2), 1);
718 printf("calling LHNET_Write(<%s>, \"%s\", %i, <%s>)\n", addressstring2, sendmessage, sendmessagelength, addressstring);
719 length = LHNET_Write(sendsock, sendmessage, sendmessagelength, &destaddress);
720 if (length == sendmessagelength)
721 printf("sent successfully\n");
723 printf("LH_Write failed, returned %i (length of message was %i)\n", length, strlen(argv[4]));
727 printf("Done sending, still listening for \"exit\"\n");
731 for (i = 0;i < numsockets;i++)
735 LHNETADDRESS_ToString(LHNET_AddressFromSocket(sock[i]), addressstring2, sizeof(addressstring2), 1);
736 printf("calling LHNET_CloseSocket(<%s>)\n", addressstring2);
737 LHNET_CloseSocket(sock[i]);
740 printf("calling LHNET_Shutdown()\n");
744 printf("Testing code for lhnet.c\nusage: lhnettest <localportnumber> [<sendnumberoftimes> <sendaddress:port> <sendmessage>]\n");