IP地址用char数组方式保存
时间: 2023-12-19 09:03:47 浏览: 116
如果你想将IP地址以`char`数组的方式保存,可以使用`IPAddress`类的`toString()`函数将其转换为字符串,然后使用`strcpy()`函数将字符串复制到`char`数组中。以下是一个示例代码:
```C++
#include <Preferences.h>
// 定义一个结构体来存储参数
struct WiFiSettings {
char ssid[32];
char password[64];
char ip[16];
char gateway[16];
char subnet[16];
uint16_t localPort;
char tcpServerIP[16];
uint16_t tcpServerPort;
};
// 创建Preferences实例
Preferences preferences;
void setup() {
// 打开Preferences存储空间,并指定名称和命名空间
preferences.begin("wifi_settings", false);
// 读取参数值
WiFiSettings wifiSettings;
preferences.getBytes("wifi_settings", &wifiSettings, sizeof(wifiSettings));
// 输出参数值到串口
Serial.begin(9600);
Serial.println("WiFi Settings:");
Serial.print("SSID: ");
Serial.println(wifiSettings.ssid);
Serial.print("Password: ");
Serial.println(wifiSettings.password);
Serial.print("IP Address: ");
Serial.println(wifiSettings.ip);
Serial.print("Gateway: ");
Serial.println(wifiSettings.gateway);
Serial.print("Subnet Mask: ");
Serial.println(wifiSettings.subnet);
Serial.print("Local Port: ");
Serial.println(wifiSettings.localPort);
Serial.print("TCP Server IP: ");
Serial.println(wifiSettings.tcpServerIP);
Serial.print("TCP Server Port: ");
Serial.println(wifiSettings.tcpServerPort);
}
void loop() {
// ...
}
void saveWiFiSettings() {
// 存储参数值
WiFiSettings wifiSettings;
strcpy(wifiSettings.ssid, "my_ssid");
strcpy(wifiSettings.password, "my_password");
IPAddress ip(192, 168, 1, 100);
strcpy(wifiSettings.ip, ip.toString().c_str()); // 将IP地址转换为字符串并复制到char数组中
IPAddress gateway(192, 168, 1, 1);
strcpy(wifiSettings.gateway, gateway.toString().c_str()); // 将网关地址转换为字符串并复制到char数组中
IPAddress subnet(255, 255, 255, 0);
strcpy(wifiSettings.subnet, subnet.toString().c_str()); // 将子网掩码转换为字符串并复制到char数组中
wifiSettings.localPort = 1234;
IPAddress tcpServerIP(192, 168, 1, 200);
strcpy(wifiSettings.tcpServerIP, tcpServerIP.toString().c_str()); // 将TCP服务器IP地址转换为字符串并复制到char数组中
wifiSettings.tcpServerPort = 5678;
preferences.putBytes("wifi_settings", &wifiSettings, sizeof(wifiSettings));
}
```
在上面的示例代码中,我们在`saveWiFiSettings()`函数中将IP地址转换为字符串,然后使用`strcpy()`函数将其复制到`char`数组中。注意,在调用`toString()`函数时,我们需要将其返回值转换为C风格的字符串,即使用`c_str()`函数。
阅读全文