Skip to content

Instantly share code, notes, and snippets.

@kgbook
Created May 20, 2019 13:01
Show Gist options
  • Save kgbook/7cdd4d91ce9c0a83af1c12e6a2ec8d2a to your computer and use it in GitHub Desktop.
Save kgbook/7cdd4d91ce9c0a83af1c12e6a2ec8d2a to your computer and use it in GitHub Desktop.
#ip #parse_ip
#include <string>
#include <sstream>
#include <iostream>
int getIP(std::string ip_str) {
if (ip_str.empty()) {
return 0;
}
std::stringstream ss(ip_str);
char delimeter;
int val[4];
ss >>val[3] >>delimeter >>val[2] >>delimeter >>val[1] >>delimeter >>val[0];
return ((val[3] << 24) | (val[2] << 16) | (val[1] << 8) | val[0]);
}
std::string getIP(int ip_num) {
int val[4];
val[3] = (ip_num >> 24) & 0xFF;
val[2] = (ip_num >>16) & 0xFF;
val[1] = (ip_num >> 8) & 0xFF;
val[0] = (ip_num) & 0xFF;
return (std::to_string(val[3]) + std::string(".") + std::to_string(val[2]) + std::string(".") + std::to_string(val[1]) + std::string(".") + std::to_string(val[0]));
}
int main() {
std::string ip_str = "10.100.1.19";
auto ip_num = getIP(ip_str);
std::cout <<ip_num <<", " <<getIP(ip_num) <<std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment