Last active
August 20, 2023 16:41
-
-
Save chiro-hiro/ee336cacf8e76635de821fa38b1bf526 to your computer and use it in GitHub Desktop.
Unsigned 32 bits IP address to string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
g++ -std=c++11 ip2str.cpp -o ip2str | |
ip2str 0xb01a8c0 0x100007f | |
*/ | |
#include <sstream> | |
#include <iostream> | |
using namespace std; | |
/* Simplest version */ | |
string ipToStr2(uint32_t ip) | |
{ | |
stringstream ipStr; | |
ipStr << (ip & 0xff) << "."; | |
ipStr << ((ip >>8) & 0xff) << "."; | |
ipStr << ((ip >>16) & 0xff) << "."; | |
ipStr << ((ip >>24) & 0xff); | |
return ipStr.str(); | |
} | |
/* Shorter version */ | |
string ipToStr(uint32_t ip) | |
{ | |
stringstream ipStr; | |
for(short c = 0; c <= 24; c += 8){ | |
ipStr << ((ip >> c) & 0xff) << ((c < 24) ? "." : ""); | |
} | |
return ipStr.str(); | |
} | |
int main(int argc, char* argv[]) | |
{ | |
string buf; | |
if(argc > 1){ | |
for(int c = 1; c < argc; c++){ | |
try{ | |
buf.assign(argv[c]); | |
uint32_t a =stoul(buf, nullptr, 0); | |
cout << c << ": " << argv[c] << "(" << a << ") IP:" << ipToStr(a) << "\n"; | |
}catch(...){ | |
cout << c << ": Error at \"" << argv[c] << "\"\n"; | |
} | |
} | |
}else{ | |
cout << "Convert 32 bits to IP address string\nUsage: ip2str 0xb01a8c0 0x100007f\n"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment