Program to convert IP address to hexadecimal in C++


Given with the input as an IP address value and the task is to represent the given IP address as its hexadecimal equivalent.

What is IP address

IP address or Internet protocol is a unique number to that uniquely describes your hardware connected to a network. Internet means over the network and protocol defines the set of rules and regulations that must be followed for connection. Because of IP address only it is possible for a system to communicate with another system over a network. There are two versions of IP that are −

  • IPv4(Internet Protocol Version 4)
  • IPv6(Internet Protocol Version 6)

IP address is represented as the sequence of numbers which are in the form −

151.101.65.121

For this conversion, below program is using the header file “arpa/inet.h” which is created for the internet operations

Example

Input-: 127.0.0.1
Ouput-: 0x7f000001
Input-: 172.31.0.2
Output-: 0xac1f0002

Algorithm

Start
Step1-> Declare function to reverse
   void reverse(char* str)
      set int len = 2
      set int r = strlen(str) – 2
      Loop While (len < r)
         call swap(str[len++], str[r++])
         Call swap(str[len++], str[r])
         Set r = r – 3
      End
   End
Step 2-> Declare function to convert IP address to hexadecimal
   void convert(int ip_add)
      declare char str[15]
      call sprintf(str, "0x%08x", ip_add)
      call reverse(str)
      print str
step 3-> In main()
   declare int ip_add = inet_addr("127.0.0.1")
   call convert(ip_add)
Stop

Example

 Live Demo

#include <arpa/inet.h>
#include <iostream>
#include <string.h>
using namespace std;
//reverse hexadecimal number
void reverse(char* str) {
   int len = 2;
   int r = strlen(str) - 2;
   while (len < r) {
      swap(str[len++], str[r++]);
      swap(str[len++], str[r]);
      r = r - 3;
   }
}
//Convert IP address to heaxdecimal
void convert(int ip_add) {
   char str[15];
   sprintf(str, "0x%08x", ip_add);
   reverse(str);
   cout << str << "\n";
}
int main() {
   int ip_add = inet_addr("127.0.0.1");
   convert(ip_add);
   return 0;
}

Output

IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT

0x7f000001

Updated on: 18-Oct-2019

543 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements