mscdex / cap

A cross-platform binding for performing packet capturing with node.js
MIT License
360 stars 46 forks source link

Listen to more than one interface #84

Closed Giuan0 closed 5 years ago

Giuan0 commented 5 years ago

Do I have to loop Cap.deviceList() devices and create a listener for each detected device to listen to all incoming packets?

mscdex commented 5 years ago

At least on Linux (not sure about Windows) you can specify the 'any' device, which has a link type of 'LINKTYPE_LINUX_SLL' instead of 'ETHERNET', so you will need to parse that format (cap currently does not have a parser for this but the layout is simple) to get to the underlying packet. For example:

function getTCPPayload(buffer, linkType) {
  var payload;
  if (linkType === 'LINKTYPE_LINUX_SLL') {
    var type = buffer.readUInt16BE(0);
    var arphd = buffer.readUInt16BE(2);
    var lladdrLen = buffer.readUInt16BE(4);
    var lladdr = buffer.toString('hex', 6, 6 + Math.min(8, lladdrLen));
    var protoType = buffer.readUInt16BE(14);
    if (protoType === PROTOCOL.ETHERNET.IPV4) {
      ret = decoders.IPV4(buffer, 16);
      if (ret.info.protocol === PROTOCOL.IP.TCP) {
        var datalen = ret.info.totallen - ret.hdrlen;
        ret = decoders.TCP(buffer, ret.offset);
        datalen -= ret.hdrlen;
        payload = buffer.toString('binary',
                                  ret.offset,
                                  ret.offset + datalen);
      }
    }
  } else if (linkType === 'ETHERNET') {
    // use built-in parsers as normal ...
  }
  return payload;
}