Post date: Jul 31, 2013 12:42:4 PM
Problem
Convert IP address(32-bit) into string format.
Solution
Pay attention to computer endianess.
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Convert ip address(32-bit) into string format.
Created Date : 31-July-2013
Last Modified :
===========================================================================
*/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
string IPAddress(unsigned int ip)
{
union Endianess{
int i;
char c;
} ;
Endianess t;
t.i = 1;
unsigned char *p = (unsigned char*)&ip;
return (t.c == 1)?
to_string(*(p + 3)) + "." +
to_string(*(p + 2)) + "." +
to_string(*(p + 1)) + "." +
to_string(*(p + 0)):
to_string(*(p + 0)) + "." +
to_string(*(p + 1)) + "." +
to_string(*(p + 2)) + "." +
to_string(*(p + 3));
}
int main(int argc, char* argv[])
{
cout << IPAddress(0x01020304) << endl;
return 0;
}
Output
1.2.3.4
Press any key to continue . . .