如何在node.js下setsockopt?

时间:2012-11-04 08:01:43

标签: node.js sockets

node.js中是否有类似setsockopt / getsockopt的套接字选项操作功能?

3 个答案:

答案 0 :(得分:6)

我正在扩展显示socketpair的{​​{1}}留下的评论。您可以使用getsockoptffi来完成此操作。我已将其重新格式化,以便轻松操作。

我编辑了我的评论,因为我必须进行一些更改才能使代码在Linux和Win32上运行。我必须创建一个node library for Windows来获取套接字句柄并将其传递给ref。请注意,Linux和Windows可能具有不同的套接字选项值

编辑:这是我正在使用的清理过的生产代码:

setsockopt

答案 1 :(得分:4)

这是我的getsockopt:

var ffi = require('ffi');
var net = require('net');
var StructType = require('ref-struct');
var ref = require('ref');

var current = ffi.Library(null, {
  'getsockopt': [ 'int', [ 'int', 'int', 'int', 'pointer', 'pointer']],
  'ntohs': ['uint16', ['uint16']],
//    const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);

});

var SOL_IP = 0;
var SO_ORIGINAL_DST = 80;
var AF_INET = 2;

var sockaddr_in = StructType([
    ['int16', 'sin_family'],
    ['uint16', 'sin_port'],
    ['uint32', 'sin_addr'],
    ['uint32', 'trash1'],
    ['uint32', 'trash2'],
]);

function get_original_dst(client) {
    var dst = new sockaddr_in;
    var dstlen = ref.alloc(ref.types.int, sockaddr_in.size);
    var r = current.getsockopt(client._handle.fd, SOL_IP, SO_ORIGINAL_DST, dst.ref(), dstlen);
    if (r === -1)
        throw new Error("getsockopt(SO_ORIGINAL_DST) error");
    if (dst.sin_family !== AF_INET)
        throw new Error("getsockopt(SO_ORIGINAL_DST) returns unknown family: " + dst.sin_family );

    // TODO: inet_ntop. inet_ntoa is _UNSAFE_
    var ipaddr = dst.ref(); ipaddr = ipaddr[4] + "." + ipaddr[5] + "." + ipaddr[6] + "." + ipaddr[7];

    return [ipaddr, current.ntohs(dst.sin_port)];
}

module.exports.get_original_dst = get_original_dst;

答案 2 :(得分:-1)

有点迟到但是这是npm https://www.npmjs.com/package/net-keepalive

上的宣传
  

提供对TCP_KEEPIDLE,TCP_KEEPINTVL,TCP_KEEPCNT

等套接字选项的高级访问
var Net = require('net')
  , NetKeepAlive = require('net-keepalive')
;

// Create a TCP Server
var srv = Net.createServer(function(s){>
  console.log('Connected %j', s.address())
  // Doesn't matter what it does
  s.pipe(s)
});

// Start on some port
srv.listen(1337, function(){
  console.log('Listening on %j', srv.address())
});

// Connect to that server
var s = Net.createConnection({port:1337}, function(){
  console.log('Connected to %j', s.address())

  //IMPORTANT: KeepAlive must be enabled for this to work
  s.setKeepAlive(true, 1000)

  // Set TCP_KEEPINTVL for this specific socket
  NetKeepAlive.setKeepAliveInterval(s, 1000)

  // and TCP_KEEPCNT
  NetKeepAlive.setKeepAliveProbes(s, 1)
});