#ifndef RESOLVE_H #define RESOLVE_H /* resolve.h - turn a dotted-quad OR a hostname into an IPv4 address. Hostname lookups go out as a DNS A query over a UDP socket to 1.1.1.1:53; the kernel owns UDP, this owns DNS. Header-only (one copy per program). */ #include "sock.h" static unsigned char _dnsbuf[200]; static unsigned char _dnssrv[4]; /* parse "A.B.C.D" into out[4]; return 1 on success */ static unsigned char parse_ip(char *s, unsigned char *out) { unsigned char i, v; for (i = 0; i < 4; i++) { if (*s < '0' || *s > '9') return 0; v = 0; while (*s >= '0' && *s <= '9') { v = (unsigned char)(v * 10 + (*s - '0')); s++; } out[i] = v; if (i < 3) { if (*s != '.') return 0; s++; } } return 1; } static unsigned char _dns_query(char *host) { unsigned char i = 0, p = 12, lblpos, len; _dnsbuf[0] = 0x12; _dnsbuf[1] = 0x34; _dnsbuf[2] = 0x01; _dnsbuf[3] = 0x00; _dnsbuf[4] = 0; _dnsbuf[5] = 1; _dnsbuf[6] = 0; _dnsbuf[7] = 0; _dnsbuf[8] = 0; _dnsbuf[9] = 0; _dnsbuf[10] = 0; _dnsbuf[11] = 0; while (host[i]) { lblpos = p++; len = 0; while (host[i] && host[i] != '.') { _dnsbuf[p++] = host[i]; i++; len++; } _dnsbuf[lblpos] = len; if (host[i] == '.') i++; } _dnsbuf[p++] = 0; _dnsbuf[p++] = 0; _dnsbuf[p++] = 1; _dnsbuf[p++] = 0; _dnsbuf[p++] = 1; return p; } static unsigned int _dns_skip(unsigned int p) { for (;;) { if (_dnsbuf[p] == 0) return p + 1; if ((_dnsbuf[p] & 0xC0) == 0xC0) return p + 2; p += _dnsbuf[p] + 1; } } static unsigned char _dns_answer(unsigned char *ip) { unsigned int p, a, an, type, rdlen; an = ((unsigned int)_dnsbuf[6] << 8) | _dnsbuf[7]; if (an == 0) return 0; p = _dns_skip(12) + 4; for (a = 0; a < an; a++) { p = _dns_skip(p); type = ((unsigned int)_dnsbuf[p] << 8) | _dnsbuf[p + 1]; p += 8; rdlen = ((unsigned int)_dnsbuf[p] << 8) | _dnsbuf[p + 1]; p += 2; if (type == 1 && rdlen == 4) { ip[0] = _dnsbuf[p]; ip[1] = _dnsbuf[p + 1]; ip[2] = _dnsbuf[p + 2]; ip[3] = _dnsbuf[p + 3]; return 1; } p += rdlen; } return 0; } /* resolve a dotted-quad or hostname into ip[4]; return 1 on success */ static unsigned char resolve(char *host, unsigned char *ip) { unsigned char s, n; if (parse_ip(host, ip)) return 1; /* already an address */ _dnssrv[0] = 1; _dnssrv[1] = 1; _dnssrv[2] = 1; _dnssrv[3] = 1; s = net_socket(SOCK_UDP); if (s == 0xFF) return 0; net_bind(s, 40000); net_connect(s, _dnssrv, 53); n = _dns_query(host); net_send(s, _dnsbuf, n); n = net_recv(s, _dnsbuf, 200); net_close(s); if (n == 0xFF) return 0; return _dns_answer(ip); } #endif