NodeMCU通过mDNS解析Raspberry的本地DNS

时间:2017-05-25 18:58:10

标签: dns raspberry-pi esp8266 nodemcu mdns

我在Raspberry Pi上设置了.local地址,可以通过地址raspberrypi.local上的PC访问。

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

我发现这个答案提到NodeMCU需要设置mDNS解析器: ESP8266 nodemcu resolving raspberry's local dns

如何在NodeMCU上设置mDNS?

1 个答案:

答案 0 :(得分:1)

找到解决方案!

这是注释代码。

您需要包含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]);
      }
    }
  }
}