c++ - 从 'const char*' 到 'uint32_t {aka unsigned int}' 的无效转换 [-fpermissive]
问题描述
我正在尝试通过使用网络掩码执行 and 操作来检查 IP 地址是否在范围内,这段代码给了我以下错误:
invalid conversion from ‘const char*’ to ‘uint32_t {aka unsigned int}’ [-fpermissive]
我是 C++ 的初学者,有什么解决办法吗?
int main() {
uint32_t ip = "192.168.2.1";
// value to check
uint32_t netip = "192.168.2.0"; // network ip to compare with
uint32_t netmask = "255.255.255.0"; // network ip subnet mask
if ( (netip & netmask) == (ip & netmask)) {
// is on same subnet...
std::cout << "On the same subnet" << std::endl;
} else {
// not on same subnet...
std::cout << "Not on the same subnet" << std::endl;
}
}
解决方案
问题出在这些线上
uint32_t ip = "192.168.2.1"; // value to check
uint32_t netip = "192.168.2.0"; // network ip to compare with
uint32_t netmask = "255.255.255.0"; // network ip subnet mask
您不能将字符串文字分配给整数变量。您需要将字符串文字的内容解析为它们的数字等价物。您可以使用类似的套接字 API 函数inet_addr()
,例如:
uint32_t ip = inet_addr("192.168.2.1"); // value to check
uint32_t netip = inet_addr("192.168.2.0"); // network ip to compare with
uint32_t netmask = inet_addr("255.255.255.0"); // network ip subnet mask
推荐阅读
- maxima - 为什么千里马没有给出解决方案?
- python - 使用 selenium 和 python 获取可用日期
- vba - 使用仅包含一个名称的请求循环遍历数据和颜色行
- python - 将PDF文件转换为.txt python 3
- spring - 为什么我在 Spring Boot 服务上使用 notnoop apns push 得到 NullPointerException?
- python - 比较同一多维数组的元素
- scala - 根据条件取 sum ini spark-scala
- c# - SQLite Xamarin/C# 插入数据
- c# - 使用 API 验证数据库中是否存在某些内容
- java - 使用 MessageFormat 生成 where 子句