main.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright (c) 2020 Cesanta Software Limited
  2. // All rights reserved
  3. //
  4. // Example captive DNS server (captive portal).
  5. // 1. Run `make`. This builds and starts a server on port 5533
  6. // 2. Run `dig -t A www.google.com -4 @localhost -p 5533`
  7. #include "mongoose.h"
  8. static const char *s_listen_url = "udp://0.0.0.0:5533";
  9. // DNS answer section. We response with IP 1.2.3.4 - you can change it
  10. // in the last 4 bytes of this array
  11. uint8_t answer[] = {
  12. 0xc0, 0x0c, // Point to the name in the DNS question
  13. 0, 1, // 2 bytes - record type, A
  14. 0, 1, // 2 bytes - address class, INET
  15. 0, 0, 0, 120, // 4 bytes - TTL
  16. 0, 4, // 2 bytes - address length
  17. 1, 2, 3, 4 // 4 bytes - IP address
  18. };
  19. static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
  20. if (ev == MG_EV_OPEN) {
  21. c->is_hexdumping = 1;
  22. } else if (ev == MG_EV_READ) {
  23. struct mg_dns_rr rr; // Parse first question, offset 12 is header size
  24. size_t n = mg_dns_parse_rr(c->recv.buf, c->recv.len, 12, true, &rr);
  25. MG_INFO(("DNS request parsed, result=%d", (int) n));
  26. if (n > 0) {
  27. char buf[512];
  28. struct mg_dns_header *h = (struct mg_dns_header *) buf;
  29. memset(buf, 0, sizeof(buf)); // Clear the whole datagram
  30. h->txnid = ((struct mg_dns_header *) c->recv.buf)->txnid; // Copy tnxid
  31. h->num_questions = mg_htons(1); // We use only the 1st question
  32. h->num_answers = mg_htons(1); // And only one answer
  33. h->flags = mg_htons(0x8400); // Authoritative response
  34. memcpy(buf + sizeof(*h), c->recv.buf + sizeof(*h), n); // Copy question
  35. memcpy(buf + sizeof(*h) + n, answer, sizeof(answer)); // And answer
  36. mg_send(c, buf, 12 + n + sizeof(answer)); // And send it!
  37. }
  38. mg_iobuf_del(&c->recv, 0, c->recv.len);
  39. }
  40. (void) fn_data;
  41. (void) ev_data;
  42. }
  43. int main(void) {
  44. struct mg_mgr mgr;
  45. mg_log_set(MG_LL_DEBUG); // Set log level
  46. mg_mgr_init(&mgr); // Initialise event manager
  47. mg_listen(&mgr, s_listen_url, fn, NULL); // Start DNS server
  48. for (;;) mg_mgr_poll(&mgr, 1000); // Event loop
  49. mg_mgr_free(&mgr);
  50. return 0;
  51. }