IPアドレスを整数に変換します
#include <iostream>
#include <sstream>
#include <vector>
uint32_t ipToUint(const std::string& ip) {
std::vector<int> parts;
std::istringstream iss(ip);
std::string part;
while (std::getline(iss, part, '.')) {
parts.push_back(std::stoi(part));
}
if (parts.size() != 4) {
throw std::invalid_argument("Invalid IP address format");
}
return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3];
}
int main() {
std::string ip = "192.168.1.1";
uint32_t ipInt = ipToUint(ip);
std::cout << "IP Address: " << ip << " => Integer: " << ipInt << std::endl;
return 0;
}
整数をIPアドレスに変換します
#include <iostream>
#include <sstream>
#include <vector>
std::string uintToIp(uint32_t ipInt) {
std::ostringstream oss;
oss << ((ipInt >> 24) & 0xFF) << '.' << ((ipInt >> 16) & 0xFF) << '.'
<< ((ipInt >> 8) & 0xFF) << '.' << (ipInt & 0xFF);
return oss.str();
}
int main() {
uint32_t ipInt = 3232235777;
std::string ip = uintToIp(ipInt);
std::cout << "Integer: " << ipInt << " => IP Address: " << ip << std::endl;
return 0;
}