为什么Node.js UDP客户端不接收消息?

我正在尝试在Node.js中编写一个多播DNS客户端。

目标是显示我运行的逻辑输出:

% dns-sd -G v4 irkitd2a8.local DATE: ---Thu 20 Mar 2014--- 20:38:21.426 ...STARTING... Timestamp A/R Flags if Hostname Address TTL 20:38:22.571 Add 2 4 irkitd2a8.local. 192.168.1.43 10 

这是引擎盖下的UDP数据包:

 % sudo tcpdump -n udp port 5353 tcpdump: data link type PKTAP tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on pktap, link-type PKTAP (Packet Tap), capture size 65535 bytes 20:38:22.450804 IP 192.168.1.37.5353 > 224.0.0.251.5353: 0 A (QU)? irkitd2a8.local. (33) 20:38:22.571411 IP 192.168.1.43.5353 > 192.168.1.37.5353: 0*- [0q] 1/0/0 A 192.168.1.43 (43) 

所以我写了这个:

 var PORT = 5353; var MULTICAST_GROUP = "224.0.0.251"; var dgram = require("dgram"); var client = dgram.createSocket("udp4"); var name = "IRKitD2A8"; var payload = new Buffer( [].concat( [ 0x00, 0x00, // ID 0x00, 0x00, // fixed 0x00, 0x01, // QDCount: number of entries in the Question Section 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ], name.length, name.split("").map( function(letter) { return letter.charCodeAt(0); }), "local".length, "local".split("").map( function(letter) { return letter.charCodeAt(0); }), 0x00, // NULL terminate [ 0x00, 0x01, // QTYPE 0x80, 0x01 // QCLASS // http://tools.ietf.org/html/draft-cheshire-dnsext-multicastdns-06#section-6.5 // Multicast DNS defines the top bit in the class field of a DNS question as the "unicast response" bit. ] ) ); client.on("message", function(message, rinfo) { console.log("received: ",message,rinfo); }); client.on("listening", function() { console.log("listening on ",client.address()); client.setBroadcast(true); client.setTTL(64); client.setMulticastTTL(64); client.setMulticastLoopback(true); client.addMembership(MULTICAST_GROUP); client.send(payload, 0, payload.length, PORT, MULTICAST_GROUP, function(err,bytes) { console.log("err: "+err+" bytes: "+bytes); // client.close(); }); }); client.on("close", function() { console.log("closed"); }); client.on("error", function(err) { console.log("error: ",err); }); client.bind(5353); 

运行这个脚本时,输出:

 % node client.js listening on { address: '0.0.0.0', family: 'IPv4', port: 5353 } err: null bytes: 33 

和tcpdump输出相同的东西:

 % sudo tcpdump -n udp port 5353 tcpdump: data link type PKTAP tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on pktap, link-type PKTAP (Packet Tap), capture size 65535 bytes 20:48:33.816076 IP 192.168.1.37.5353 > 224.0.0.251.5353: 0 A (QU)? IRKitD2A8.local. (33) 20:48:33.853892 IP 192.168.1.43.5353 > 192.168.1.37.5353: 0*- [0q] 1/0/0 A 192.168.1.43 (43) 

所以它看起来像dns-sd一样正确发送相同的数据包,并且接收到相同的内容,但脚本的message事件处理程序不会触发。 为什么? 如何解决这个问题,并输出收到的数据包?

我在MacOSX10.9,Node.js 0.10.25

防火墙。

我做了:

  1. 在“系统预置”>“安全和隐私”>“防火墙”的进程列表中有几个名为node的条目,所以我删除了所有节点条目。
  2. 重新启动MacOSX
  3. 重新启动脚本
  4. 我批准了一个对话框,问我是否批准节点侦听连接。
  5. 问题解决了!

对不起大家。

Interesting Posts