tls.js (1272B)
1 'use strict' 2 3 const tls = require('tls') 4 const dnsPacket = require('..') 5 6 var response = null 7 var expectedLength = 0 8 9 function getRandomInt (min, max) { 10 return Math.floor(Math.random() * (max - min + 1)) + min 11 } 12 13 const buf = dnsPacket.streamEncode({ 14 type: 'query', 15 id: getRandomInt(1, 65534), 16 flags: dnsPacket.RECURSION_DESIRED, 17 questions: [{ 18 type: 'A', 19 name: 'google.com' 20 }] 21 }) 22 23 const context = tls.createSecureContext({ 24 secureProtocol: 'TLSv1_2_method' 25 }) 26 27 const options = { 28 port: 853, 29 host: 'getdnsapi.net', 30 secureContext: context 31 } 32 33 const client = tls.connect(options, () => { 34 console.log('client connected') 35 client.write(buf) 36 }) 37 38 client.on('data', function (data) { 39 console.log('Received response: %d bytes', data.byteLength) 40 if (response == null) { 41 if (data.byteLength > 1) { 42 const plen = data.readUInt16BE(0) 43 expectedLength = plen 44 if (plen < 12) { 45 throw new Error('below DNS minimum packet length') 46 } 47 response = Buffer.from(data) 48 } 49 } else { 50 response = Buffer.concat([response, data]) 51 } 52 53 if (response.byteLength >= expectedLength) { 54 console.log(dnsPacket.streamDecode(response)) 55 client.destroy() 56 } 57 }) 58 59 client.on('end', () => { 60 console.log('Connection ended') 61 })