Library to resolve text URLs to IP addresses (IPv4)
Dependents: NetworkSocketAPI NetworkSocketAPI Nucleo-AWS-IoT-mbed
Diff: DnsQuery.cpp
- Revision:
- 13:9c6e83b0ae7c
- Parent:
- 12:e23ef3dab4b9
- Child:
- 14:248f32a9c48d
--- a/DnsQuery.cpp Mon Feb 29 15:19:32 2016 +0000 +++ b/DnsQuery.cpp Mon Feb 29 15:20:55 2016 +0000 @@ -48,20 +48,20 @@ } -static bool parseRR(uint8_t *resp, int& c, char* adr ) +static bool parseRR(uint8_t *resp, int &c, char *adr) { int n = 0; - while( (n=resp[c++]) != 0) { + while((n=resp[c++]) != 0) { if ((n & 0xc0) != 0) { // This is a link c++; break; } else { // skip this segment, not interested in string domain names - c+= n; + c+= n; } } - + int TYPE = (((int)resp[c])<<8) + resp[c+1]; int CLASS = (((int)resp[c+2])<<8) + resp[c+3]; int RDLENGTH = (((int)resp[c+8])<<8) + resp[c+9]; @@ -71,27 +71,26 @@ sprintf(adr,"%d.%d.%d.%d", resp[c], resp[c+1], resp[c+2], resp[c+3]); c+= RDLENGTH; return true; - } else { } c+= RDLENGTH; - + return false; } -static bool resolve(unsigned char* resp, char* ipaddress) +static bool resolve(unsigned char *resp, char *ipaddress) { - + int ID = (((int)resp[0]) <<8) + resp[1]; int QR = resp[2] >>7; int Opcode = (resp[2]>>3) & 0x0F; int RCODE = (resp[3] & 0x0F); int ANCOUNT = (((int)resp[6])<<8)+ resp[7]; - + if ((ID != 1) || (QR != 1) || (Opcode != 0) || (RCODE != 0)) { return false; } - + int c = 12; int d; // Skip domain question @@ -99,14 +98,14 @@ c+=d; } c+= 4; // skip QTYPE and QCLASS - + // Here comes the resource record for (int ans = 0 ; ans < ANCOUNT; ans++) { if (parseRR(resp, c, ipaddress)) { return true; } } - + return false; } @@ -143,17 +142,20 @@ int32_t dnsQuery(UDPSocket *socket, const char *hostname, char *ipaddress) { int len = 0; - if (hostname == NULL) + if (hostname == NULL) { return false; + } len = strlen(hostname); - if ((len >128) || (len == 0)) + if ((len > 128) || (len == 0)) { return false; - + } + int packetlen = /* size of HEADER structure */ 12 + /* size of QUESTION Structure */5 + len + 1; uint8_t *packet = new uint8_t[packetlen]; /* this is the UDP packet to send to the DNS */ - if (packet == NULL) + if (packet == NULL) { return false; - + } + // Fill the header memset(packet, 0, packetlen); packet[1] = 1; // ID = 1 @@ -174,40 +176,41 @@ packet[cnt] = 0; } } - + // Terminate this domain name with a zero entry packet[c++] = 0; - + // Set QTYPE packet[c++] = 0; packet[c++] = 1; // Set QCLASS packet[c++] = 0; packet[c++] = 1; - + if (socket->send(packet, packetlen) < 0) { delete packet; return false; } delete packet; - + packet = new uint8_t [1024]; - + // Receive the answer from DNS int response_length = 0; response_length = socket->recv(packet, 1024); - + if (response_length > 0 ) { if (!resolve(packet, ipaddress)) { delete packet; return NS_ERROR_DNS_FAILURE; } - + // cleanup and return delete packet; return 0; } + delete packet; return NS_ERROR_DNS_FAILURE; }