exports.is_acl_allowed = function (connection) { const plugin = this; if (!plugin.acl_allow) { return false; } if (!plugin.acl_allow.length) { return false; } const ip = connection.remote.ip; for (let i=0; i < plugin.acl_allow.length; i++) { const item = plugin.acl_allow[i]; connection.logdebug(plugin, `checking if ${ip} is in ${item}`); const cidr = plugin.acl_allow[i].split('/'); const c_net = cidr[0]; const c_mask = cidr[1] || 32; if (!net.isIP(c_net)) continue; // bad config entry if (net.isIPv4(ip) && net.isIPv6(c_net)) continue; if (net.isIPv6(ip) && net.isIPv4(c_net)) continue; if (ipaddr.parse(ip).match(ipaddr.parse(c_net), c_mask)) { connection.logdebug(plugin, `checking if ${ip} is in ${item}: yes`); return true; } } return false; }
'IPv6, Prefix': function (test) { /* for x-*-ip headers */ test.expect(2); // it must fail as of not valide test.ok(!net.isIPv6('IPv6:2001:db8:85a3::8a2e:370:7334')); // must okay! test.ok(net.isIPv6('2001:db8:85a3::8a2e:370:7334')); test.done(); },
var UdpProxy = function (options) { "use strict"; var proxy = this; var localUdpType = 'udp4'; var localfamily = 'IPv4'; var serverPort = options.localport || 0; var serverHost = options.localaddress || '0.0.0.0'; var proxyHost = options.proxyaddress || '0.0.0.0'; this.tOutTime = options.timeOutTime || 10000; this.family = 'IPv4'; this.udpType = 'udp4'; this.host = options.address || 'localhost'; this.port = options.port || 41234; this.connections = {}; if (options.ipv6) { this.udpType = 'udp6'; this.family = 'IPv6'; proxyHost = net.isIPv6(options.proxyaddress) ? options.proxyaddress : '::0'; } this._details = { target: { address: this.host, family: this.family, port: this.port } }; this._detailKeys = Object.keys(this._details); if (options.localipv6) { localUdpType = 'udp6'; serverHost = net.isIPv6(options.localaddress) ? options.localaddress : '::0'; } this._server = dgram.createSocket(localUdpType); this._server.on('listening', function () { var details = proxy.getDetails({server: this.address()}); setImmediate(function() { proxy.emit('listening', details); }); }).on('message', function (msg, sender) { var client = proxy.createClient(msg, sender); if (!client._bound) client.bind(0, proxyHost); else client.emit('send', msg, sender); }).on('error', function (err) { this.close(); proxy.emit('error', err); }).on('close', function () { proxy.emit('close'); }).bind(serverPort, serverHost); };
/** * Your context for a client periodically sending to 1 server. Use * * Syntax : * 1/ var client = Collectd(); * 2/ var client = Collectd(int, string, int, string); * 3/ var client = Collectd(int, object, ignored, string); * * All arguments are optional (like in syntax 1) * Syntax 1 * no args (they are all optional) * Syntax 2 * arg1 is the interval between 2 sending data to Collectd servers * arg2 is the Collectd server name * arg3 is the Collectd server port * arg4 is the host name used in Collectd values * Syntax 3 * arg1 is the interval between 2 sending data to Collectd servers * arg2 is an array like this : [ ['host1', port], ['host2', port], ...] * arg3 is ignored. * arg4 is the host name used in Collectd values */ function Collectd(interval, host, port, hostname) { this.interval = interval || 10000; this.serverHosts = []; this.plugins = {}; this.hostname = typeof hostname !== 'undefined' ? hostname : os.hostname(); /* Configure Collectd hosts to send metrics to */ switch(typeof(host)) { case 'object': for (var i=0; i < host.length; i++) { var h = host[i]; this.serverHosts[this.serverHosts.length] = { 'host': h[0], 'port': (h[1] || 25826) }; } break; case 'string': this.serverHosts = [{ 'host': host, 'port': (port || 25826) }]; break; default: this.serverHosts = [{ 'host': 'ff18::efc0:4a42', 'port': 25826 }]; } /* Create the network sockets for each host */ for (var i=0; i < this.serverHosts.length; i++) { this.serverHosts[i].sock = dgram.createSocket(net.isIPv6(this.serverHosts[i].host) ? 'udp6' : 'udp4'); this.serverHosts[i].sock.on('error', function(e) { console.error(e.stack || e.message || e); }); } setInterval(this.send.bind(this), this.interval); };
endpoints.forEach(function(endpoint) { if(net.isIPv4(endpoint.src)) { endpoint.src_type = "ipv4"; } else if(net.isIPv6(endpoint.src)) { endpoint.src_type = "ipv6"; } else { endpoint.src_type = "hostname"; } if(net.isIPv4(endpoint.dst)) { endpoint.dst_type = "ipv4"; } else if(net.isIPv6(endpoint.dst)) { endpoint.dst_type = "ipv6"; } else { endpoint.dst_type = "hostname"; } });
(next) => { if (target.match(/[a-z]/i) && !target.match(/\//) && !net.isIPv6(target)) { dns.resolve4(target, next); } else { next(null,[[target]]); } }
var getIpInformation = function(ipAddress, keys, callback) { if (typeof keys === 'function') { callback = keys; keys = []; } if (!net.isIPv4(ipAddress) && !net.isIPv6(ipAddress)) { return callback('Invalid IP Address.'); } http.get(ipInfoHost + ipAddress, function(res) { var info = ''; res.on('data', function(chunk) { info += chunk; }); res.on('end', function(){ result = {}; info = JSON.parse(info); if ( keys.length > 0 ) { for(var i = 0; i < keys.length; i++) { result[keys[i]] = info[keys[i]]; } } else { result = info; } callback(null, result); }); res.on('error', function(err) { callback(err); }); }); }
net_utils.get_ips_by_host(addr.exchange, (err2, addresses2) => { pending_queries--; if (!txn) return; if (err2 && err2.length === 2) { results.add(plugin, {msg: err2[0].message}); connection.logdebug(plugin, domain + ': MX ' + addr.priority + ' ' + addr.exchange + ' => ' + err2[0].message); check_results(); return; } connection.logdebug(plugin, domain + ': MX ' + addr.priority + ' ' + addr.exchange + ' => ' + addresses2); for (let i=0; i < addresses2.length; i++) { // Ignore anything obviously bogus if (net.isIPv4(addresses2[i])){ if (plugin.re_bogus_ip.test(addresses2[i])) { connection.logdebug(plugin, addr.exchange + ': discarding ' + addresses2[i]); continue; } } if (net.isIPv6(addresses2[i])){ if (net_utils.ipv6_bogus(addresses2[i])) { connection.logdebug(plugin, addr.exchange + ': discarding ' + addresses2[i]); continue; } } records[addresses2[i]] = 1; } check_results(); });
util_vm.ipsFromNICs(vm.nics).forEach(function (ip) { if (net.isIPv6(ip)) { v6rules[vm2.uuid].in.pass.tcp[ip] = [ 80, 125 ]; } else { v4rules[vm2.uuid].in.pass.tcp[ip] = [ 80, 125 ]; } });
util_vm.ipsFromNICs(vm.nics).forEach(function (ip) { if (net.isIPv6(ip)) { v6rules[vm4.uuid]['in'].pass.tcp[ip] = [ 8080 ]; } else { v4rules[vm4.uuid]['in'].pass.tcp[ip] = [ 8080 ]; } });
Config.get("listen").forEach(function (bind) { if (!bind.io) { return; } var id = bind.ip + ":" + bind.port; if (id in srv.ioServers) { Logger.syslog.log("[WARN] Ignoring duplicate listen address " + id); return; } var io = null; if (id in srv.servers) { io = srv.ioServers[id] = sio.listen(srv.servers[id]); } else { if (net.isIPv6(bind.ip) || bind.ip === "::") { /** * Socket.IO won't bind to a v6 address natively. * Instead, we have to create a node HTTP server, bind it * to the desired address, then have socket.io listen on it */ io = srv.ioServers[id] = sio.listen( require("http").createServer().listen(bind.port, bind.ip) ); } else { io = srv.ioServers[id] = sio.listen(bind.port, bind.ip); } } if (io) { io.set("log level", 1); io.set("authorization", handleAuth); io.on("connection", handleConnection); } });
listen: function (port, addr, cb) { cb = cb || noop var err if (net.isIPv6(addr)) { err = server.bind6(addr, port) } else { err = server.bind(addr, port) } if (err) { server.close() cb(err) return } // 512 connections allowed in backlog server.listen(511) server.onconnection = function (err, client) { if (err) { return console.error(new Error('error connected:' + err)) } onConnect(Handle(client, noop)) } return server },
function SipFakeStack (config) { var self = this; if (!config.server) { throw '(SipFakeStack) You need at least to specify a valid IPv4/6 target'; } this.server = config.server || null; this.port = config.port || 5060; this.transport = config.transport || 'UDP'; // this.lport = config.lport || utils.randomPort(); this.lport = config.lport || null; this.srcHost = config.srcHost; this.timeout = config.timeout || 8000; this.wsPath = config.wsPath || null; this.tlsType = config.tlsType || 'SSLv3'; this.domain = config.domain || null; this.onlyFirst = config.onlyFirst || true; if (net.isIPv6(config.server) && !config.srcHost) { this.srcHost = utils.randomIP6(); } else if (!config.srcHost) { this.srcHost = utils.randomIP(); } }
/** * Sends Socks v5 final handshake request. */ sendSocks5CommandRequest() { const buff = new smart_buffer_1.SmartBuffer(); buff.writeUInt8(0x05); buff.writeUInt8(constants_1.SocksCommand[this._options.command]); buff.writeUInt8(0x00); // ipv4, ipv6, domain? if (net.isIPv4(this._options.destination.host)) { buff.writeUInt8(constants_1.Socks5HostType.IPv4); buff.writeBuffer(ip.toBuffer(this._options.destination.host)); } else if (net.isIPv6(this._options.destination.host)) { buff.writeUInt8(constants_1.Socks5HostType.IPv6); buff.writeBuffer(ip.toBuffer(this._options.destination.host)); } else { buff.writeUInt8(constants_1.Socks5HostType.Hostname); buff.writeUInt8(this._options.destination.host.length); buff.writeString(this._options.destination.host); } buff.writeUInt16BE(this._options.destination.port); this._nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; this._socket.write(buff.toBuffer()); this.state = constants_1.SocksClientState.SentFinalHandshake; }
function makeUdpTransport(options, callback) { function onMessage(data, rinfo) { var msg = parseMessage(data); if(msg && checkMessage(msg)) { if(msg.method) { msg.headers.via[0].params.received = rinfo.address; if(msg.headers.via[0].params.hasOwnProperty('rport')) msg.headers.via[0].params.rport = rinfo.port; } callback(msg, {protocol: 'UDP', address: rinfo.address, port: rinfo.port}); } } var address = options.address || '0.0.0.0'; var port = options.port || 5060; var socket = dgram.createSocket(net.isIPv6(options.address) ? 'udp6' : 'udp4', onMessage); socket.bind(port, address); return { open: function(remote, error) { return { send: function(m) { var s = stringify(m); socket.send(new Buffer(s, 'ascii'), 0, s.length, remote.port, remote.address); }, local: {protocol: 'UDP', address: address, port: port}, release : function() {} }; }, destroy: function() { socket.close(); } } }
var req = dns.lookup('::1', function(err, ip, family) { if (err) throw err; assert.ok(net.isIPv6(ip)); assert.strictEqual(family, 6); done(); });
/* * Returns true if the IP passed in is in any of the RFC1918 private * address spaces */ function isRFC1918(ip) { var num = ip; if (net.isIPv6(ip)) { return false; } if (isNaN(num)) { num = addressToNumber(ip); } // 10.0.0.0/8: 10.0.0.0 - 10.255.255.255 if (num >= 167772160 && num <= 184549375) { return true; } // 172.16.0.0/12: 172.16.0.0 - 172.31.255.255 if (num >= 2886729728 && num <= 2887778303) { return true; } // 192.168.0.0/16: 192.168.0.0 - 192.168.255.255 if (num >= 3232235520 && num <= 3232301055) { return true; } return false; }
app.get('/DNS/:method/:id', function (req, res) { var attrIP = req.params.id; var method = req.params.method; attrIP = attrIP.toString(); method = method.toString().toUpperCase(); if (method == "PTR" && !net.isIP(attrIP)) { res.json({ "datetime": Date(), "method": method, "host": attrIP, "err": { code: 'BADFAMILY' }, "ipv": (net.isIP(attrIP) ? (net.isIPv6(attrIP) ? 6 : 4) : 0), "query": req.query }); } else dns.resolve(attrIP, method, function (err, domains) { res.json({ "datetime": Date(), "method": method, "host": attrIP, "result": domains, "err": err, "ipv": (net.isIP(attrIP) ? (net.isIPv6(attrIP) ? 6 : 4) : 0), "query": req.query }); }); });
/** * Check whether the specified hostname is valid. * * @param hostname {string} Host name (excluding port) of requested resource. * @return {boolean} Whether the requested resource can be accessed. */ function isValidHostName(hostname) { return !!( regexp_tld.test(hostname) || net.isIPv4(hostname) || net.isIPv6(hostname) ); }
var req = dns.lookup('::1', function(err, ip, family) { test.ifError(err); test.ok(net.isIPv6(ip)); test.strictEqual(family, 6); test.done(); });
Gossiper.prototype._generatePeerName = function() { if (net.isIPv6(this.address)) { return '[' + this.address + ']' + ':' + this.port; } return this.address + ':' + this.port; }
var ip2iface = function (ip_w_mask) { var parts = ip_w_mask.split(/\//); if(parts == null) return null; if(net.isIPv4(parts[0])) { var ip = parts[0], mask = (parts[1] === undefined) ? 32 : parseInt(parts[1]); if(mask > 32 || mask < 0) return null; var p = ip.split(/\./).map(function (x) { return parseInt(x); }); var nm = [ 0, 0, 0, 0 ]; for (var i=0; i<4; i++) { var bits = mask - (i * 8); if(bits > 7) nm[i] = 255; else if(bits > 0) nm[i] = 255 >> (8-bits) << (8-bits); } var bc = p.map(function(x,i) { return x | (~nm[i] & 0xff); }); var nw = p.map(function(x,i) { return x & nm[i]; }); return { 'ip': p.join('.'), 'netmask': nm.join('.'), 'broadcast': bc.join('.'), 'network': nw.join('.') }; } else if(net.isIPv6(parts[0])) { return { 'ip': parts[0], 'prefixlen': parts[1] }; } return null; };
rvm.ips.forEach(function (ip) { if (!mod_net.isIPv4(ip) && !mod_net.isIPv6(ip)) { err = new VError('Invalid IP address: %s', ip); err.details = vm; throw err; } });
CoAPServer.prototype.listen = function(port, address, done) { var that = this if (port == undefined) { port = parameters.coapPort } if (typeof port === 'function') { done = port port = parameters.coapPort } if (typeof address === 'function') { done = address address = null } if (this._sock) { if (done) done(new Error('Already listening')) else throw new Error('Already listening') return this } if (address && net.isIPv6(address)) this._options.type = 'udp6' if (!this._options.type) this._options.type = 'udp4' if (process.version.indexOf('v0.10') === -1) { this._sock = dgram.createSocket({type: this._options.type, reuseAddr : true}, handleRequest(this)) } else { this._sock = dgram.createSocket(this._options.type, handleRequest(this)) } this._sock.on('error', function(error) { that.emit('error', error) }) this._sock.bind(port, address || null, function () { if (that._multicastAddress) { that._sock.setMulticastLoopback(true) if (that._multicastInterface) { that._sock.addMembership(that._multicastAddress, that._multicastInterface) } else { that._sock.addMembership(that._multicastAddress) } } if (done) done() }) this._port = port this._address = address return this }
AbstractGeocoder.prototype.geocode = function(value, callback) { if (typeof this._geocode != 'function') { throw new Error(this.name + ' does not support geocoding'); } if (net.isIPv4(value) && (!this.supportIPv4 || this.supportIPv4 == 'undefined')) { throw new Error(this.name + ' does not support geocoding IPv4'); } if (net.isIPv6(value) && (!this.supportIPv6 || this.supportIPv6 == 'undefined')) { throw new Error(this.name + ' does not support geocoding IPv6'); } if (this.supportAddress === false && (!net.isIPv4(value) && !net.isIPv6(value))) { throw new Error(this.name + ' does not support geocoding address'); } return this._geocode(value, callback); };
function ReadableAdditiveSharingMessage(buffer) { /** * The extracted IP address. * * @member {string} core.protocol.hydra.ReadableAdditiveSharingMessage~_ip */ this._ip = null; /** * The extracted payload for the CREATE_CELL_ADDITIVE message. * * @member {Buffer) core.protocol.hydra.ReadableAdditiveSharingMessage~_payload */ this._payload = null; /** * The extracted port. * * @member {number} core.protocol.hydra.ReadableAdditiveSharingMessage~_port */ this._port = null; var addressIndicator = buffer[0]; var portFrom = 5; var ipError = false; var ip = ''; if (addressIndicator === MessageByteCheatsheet.ipv4) { ip = buffer.slice(1, 5).toJSON().join('.'); if (!net.isIPv4(ip)) { ipError = true; } } else if (addressIndicator == MessageByteCheatsheet.ipv6) { for (var i = 0; i < 8; i++) { ip += buffer.slice(i * 2 + 1, i * 2 + 3).toString('hex'); if (i !== 7) { ip += ':'; } } if (!net.isIPv6(ip)) { ipError = true; } portFrom = 17; } else { throw new Error('ReadableAdditiveSharingMessage: Malformed address indicator'); } if (ipError) { throw new Error('ReadableAdditiveSharingMessage: Malformed IP'); } this._ip = ip; this._port = buffer.readUInt16BE(portFrom); this._payload = buffer.slice(portFrom + 2); }
return this._test('hostname', undefined, function (value, state, options) { if ((value.length <= 255 && regex.test(value)) || Net.isIPv6(value)) { return null; } return Errors.create('string.hostname', { value: value }, state, options); });
server.start(function () { var expectedBoundAddress = '0.0.0.0'; if (Net.isIPv6(server.listener.address().address)) { expectedBoundAddress = '::'; } expect(server.info.address).to.equal(expectedBoundAddress); done(); });
function makeUdpTransport(options, callback) { util.debug('makeUdpTransport with '+util.inspect(options)); function onMessage(data, rinfo) { var msg = parseMessage(data); if (!msg) return; if(msg.method) { msg.headers.via[0].params.received = rinfo.address; if(msg.headers.via[0].params.hasOwnProperty('rport')) msg.headers.via[0].params.rport = rinfo.port; } callback(msg, {protocol: 'UDP', address: rinfo.address, port: rinfo.port}); } var socket = dgram.createSocket(net.isIPv6(options.address) ? 'udp6' : 'udp4', onMessage); socket.on('error', function() {}); if (socket.setSndBuf) { // I've added a bunch of socket options to my build of node.js, sorry socket.setSndBuf(1024*1024); socket.setRcvBuf(1024*1024); } try { socket.bind(options.port || 5060, options.address); } catch (e) { return false; } var local = {protocol: 'UDP', address: socket.address().address, port: socket.address().port}; return { open: function(remote, error) { function cb(err) { if (err) error(err); } return { send: function(m) { if (!socket) return; if (typeof m=="object") { if(m.method) { m.headers.via[0].host = this.local.address; m.headers.via[0].port = options.port; m.headers.via[0].protocol = this.local.protocol; } options.logger && options.logger.send && options.logger.send(m, target); m = new Buffer(stringify(m), 'ascii'); } //console.log("UDP SEND: "+m.toString()); socket.send(m, 0, m.length, remote.port, remote.address, cb); }, release: function() {}, local: local, } }, destroy: function() { if (socket) socket.close(); socket=false; }, }; }
exports.validate = function(ip) { var version = net.isIP(ip); switch (version) { case 4: return net.isIPv4(ip); case 6: return net.isIPv6(ip); default: return false; } };