Created
January 12, 2019 09:40
-
-
Save tksugimoto/da83e4da3302ba9ff31e73df4d73495e to your computer and use it in GitHub Desktop.
自ホスト以外からのTCPリクエストを拒否する
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
const net = require('net'); | |
const server = net.createServer(); | |
server.on('listening', () => { | |
const { | |
address, | |
port, | |
} = server.address(); | |
console.info(`Server started. (IP:port = ${address}:${port})`); | |
}); | |
const okHttpResponse = `HTTP/1.0 200 OK | |
ok | |
`; | |
const ngHttpResponse = `HTTP/1.0 403 Forbidden | |
ng | |
`; | |
server.on('connection', connection => { | |
const { | |
remoteAddress, | |
localAddress, | |
} = connection; | |
// 自ホストからのリクエスト | |
// 1. 127.0.0.0/8 (127.0.0.1 や 127.1.2.3 など) 宛にリクエストした場合 | |
// 2. 自 IPアドレス宛の通信 (192.168.0.13 や 192.168.99.1 など) | |
const fromSelfHost = remoteAddress === '127.0.0.1' || remoteAddress === localAddress; | |
connection.once('data', data => { | |
const requestLine = data.toString().split(/[\r\n]/)[0]; | |
console.info({ | |
remoteAddress, | |
localAddress, | |
requestLine, | |
fromSelfHost, | |
}); | |
}); | |
connection.end(fromSelfHost ? okHttpResponse : ngHttpResponse); | |
}); | |
server.listen(3000, '0.0.0.0'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment