NodeMCU通过mDNS解析Raspberry的本地DNS

NodeMCU resolving Raspberry's local DNS through mDNS

我已经在 Raspberry Pi 上设置了 .local 地址,可以从地址 raspberrypi.local 上的 PC 访问它。

现在我希望能够使用其 .local 地址从 NodeMCU 向 Raspberry 发出 HTTP 请求。

我发现这个答案提到 NodeMCU 需要设置 mDNS 解析器:

如何在 NodeMCU 上设置 mDNS?

找到解决方案!

这是注释代码。

您需要包含 ESP8266WiFiESP8266mDNS 库。

// hostString will be used to identify this device, 
// but not relevant as we're not providing mDNS services
char hostString[16] = {0};

void findMDNS() {
  // Need to make sure that we're connected to the wifi first
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    Serial.print(".");
  } 

  if (!MDNS.begin(hostString)) {
    Serial.println("Error setting up MDNS responder!");
  }

  // We now query our network for 'device-info' service
  // over tcp, and get the number of available devices 
  int n = MDNS.queryService("device-info", "tcp");
  if (n == 0) {
    Serial.println("no services found");
  }
  else {
    for (int i = 0; i < n; ++i) {
      // Going through every available service,
      // we're searching for the one whose hostname 
      // matches what we want, and then get its IP
      if (MDNS.hostname(i) == RASPBERRY_HOSTNAME) {
        JENKINS_HOST = String(MDNS.IP(i)[0]) + String(".") +\
          String(MDNS.IP(i)[1]) + String(".") +\
          String(MDNS.IP(i)[2]) + String(".") +\
          String(MDNS.IP(i)[3]);
      }
    }
  }
}