Arduino Ethernet库中的IPAddress()有什么好处?

4
Arduino默认的以太网库类包含一个IPAddress变量类型。这个IPAddress是用来做什么的?我为什么要使用它,为什么在官方示例中没有用于网关和子网IP?
1个回答

3

就像你所说,它是一种变量类型(例如int(整数)),可以存储IP地址。使用整数时,无法添加IP地址中需要的.s。此外,库只接受整数,因为用字符串表示事情可能会“变得混乱”。例如,如果您在字符串中有1,则无法将其与另一个数字相加。但是,如果您具有值为1的整数变量类型,则可以轻松添加它们。


我该如何使用它?:

Arduino的EthernetIpAdress页面上,有以下代码:

 #include <Ethernet.h>
 
 // network configuration.  gateway and subnet are optional.
 
  // the media access control (ethernet hardware) address for the shield:
 byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };  
 // the router's gateway address:
 byte gateway[] = { 10, 0, 0, 1 };
 // the subnet:
 byte subnet[] = { 255, 255, 0, 0 };
 
 EthernetServer server = EthernetServer(23);
 
 //the IP address is dependent on your network
 IPAddress ip(192,168,1,1);
 void setup()
 {
   // initialize the ethernet device
   Ethernet.begin(mac, ip, gateway, subnet);
 
   // start listening for clients
   server.begin();
 }
 void loop()
 {
   //print out the IP address
   Serial.println(myIPaddress);
 }

IPAddress ip(192,168,1,1);这一行中,它创建了一个变量来保存IP地址。在Ethernet.begin(mac, ip, gateway, subnet);这一行中,变量被查找并赋值给Ethernet库。我不知道它的优势是什么,除了尝试防止人们使用整数类型并使其看起来更加清晰。它可以查找自动分配的IP地址,然后存储它以便以后使用,所以如果它进入“空闲模式”,它可以请求相同的IP地址,因此它几乎像一个动态IP,不会干扰其他设备,并且在按下重置按钮时会重置。我确定它有一些用途,但我想不出其中的一个。我只是想告诉你它是什么以及如何使用它。虽然我认为,如果您希望它易于更改或更易于用户阅读,那么只需使用#define IPaddress 192.168.1.1或类似的内容即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接