Vinay Shukla
Vinay Shukla

Reputation: 1844

Fixing Endianess error in inet_ntoa while converting an IP shows reversed value

Following is the code that will convert the IP from a uint32_t to IP in string but it gives the reverse of the string due to Endianess how can I overcome this.

Program

#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>

using namespace std;

int main()
{
  uint32_t ip_in_decimal = 172694014;
  struct in_addr addr1;
  addr1.s_addr = ip_in_decimal;
  std::string bpu_ip_ran = inet_ntoa(addr1);
  std::cout<<bpu_ip_ran<<std::endl;

  return 0;
}

Output

./a.out
1.1.168.192 // Reverse of the IP value 192.168.1.1 

Upvotes: 1

Views: 607

Answers (1)

Adrian W
Adrian W

Reputation: 5026

htonl is your friend:

addr1.s_addr = htonl(ip_in_decimal);

Upvotes: 2

Related Questions