Created
August 18, 2017 08:24
-
-
Save MaBecker/ae9dade26b44524e076ca19f5fd72fab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Captive Portal | |
var http = require('http'); | |
var Wifi = require('Wifi'); | |
var dgram = require('dgram'); | |
var server = dgram.createSocket('udp4'); | |
var SSID = 'CaptivePortalTest'; | |
var authMode = 'open'; | |
var password = null; | |
var portHTTP = 80; | |
var portDNS = 53; | |
var dnsIPStr = '192.168.4.1'; | |
var dnsIP = dnsIPStr.split('.').map(n => String.fromCharCode(parseInt(n, 10))).join(''); | |
var page = '<html><body><H1>Hello World</H1></body></html>'; | |
// get Query name out of message | |
// offset = 12 | |
// end \x00 | |
function dnsQname(msg) { | |
var i = 12; | |
var qname = ''; | |
while ( msg[i] !== '\x00' ) { | |
qname += msg[i]; | |
i++; | |
} | |
return qname + '\x00'; | |
} | |
/* | |
1. line header | |
2. line query | |
3. line resource | |
*/ | |
function dnsResponse(msg,dns_ip){ | |
return msg[0]+msg[1] + '\x81\x80'+'\x00\x01'+'\x00\x01'+'\x00\x00\x00\x00' + | |
dnsQname(msg) + '\x00\x01' + '\x00\x01' + | |
'\xc0\x0c'+'\x00\x01'+'\x00\x01'+'\x00\x00\x00\xf9'+'\x00\x04' + dns_ip ; | |
} | |
function startDNSServer(port){ | |
server.on('error', (err) => { | |
server.close(); | |
}); | |
server.on('message', (msg, info) => { | |
// we only serve ip4 | |
if ( msg[msg.length-3] === '\x01') { | |
server.send(dnsResponse(msg,dnsIP),info.port,info.address); | |
} | |
}); | |
server.bind(port); | |
} | |
// start http server | |
function startHttpServer(port){ | |
var server = http.createServer(function (req, res) { | |
accept = req.headers.Accept || ''; | |
if (accept !== '*\/*') { | |
res.writeHead(200, {'Content-Type': 'text/html'}); | |
res.end(page); | |
} else { // redirect to the Setup page | |
res.writeHead(302, {'Location': 'http://192.168.4.1', | |
'Content-Type': 'text/plain'}); | |
res.end(); | |
} | |
}); | |
server.listen(port); | |
} | |
// start beeing a access point | |
function startAccessPoint(ssid,authMode, password){ | |
Wifi.startAP(ssid,{"authMode" : authMode,"password" : password}); | |
} | |
// stop beeing connected to a access point | |
function disconnectStation(){ | |
Wifi.disconnect(); | |
} | |
function start(){ | |
disconnectStation(); | |
startAccessPoint('CaptivePortalTest','open',null); | |
startHttpServer(80); | |
startDNSServer(53); | |
} | |
setTimeout(start,1000); |
Author
MaBecker
commented
Aug 18, 2017
Nice work
I completed your work: https://github.com/tombueng/EspruinoDocs/blob/master/modules/WifiManager.js
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment