Skip to content

Instantly share code, notes, and snippets.

@chiro-hiro

chiro-hiro/ip2str.cpp

Last active Feb 14, 2018
Embed
What would you like to do?
Unsigned 32 bits IP address to string
/*
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
You can’t perform that action at this time.