Open In App

Program to convert IP address to hexadecimal

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an IP Address and task is to change the IP address equivalent to the hexadecimal value. Examples:

Input  : 127.0.0.1
Output : 0x7f000001

Input : 172.31.0.2
Output : 0xac1f0002

Explanation: Using the Library function to convert the IP address into the hexadecimal value we use the ” arpa/inet.h “ header file. The inet_addr() function shall convert the string in the standard IPv4 dotted decimal notation, to an integer value suitable for use as an Internet address.

C++
// C++ program for IP to
// hexadecimal conversion
#include <arpa/inet.h>
#include <iostream>
#include <string.h>
using namespace std;

// function for reverse hexadecimal number
void reverse(char* str)
{
    // l for swap with index 2
    int l = 2;
    int r = strlen(str) - 2;

    // swap with in two-2 pair
    while (l < r) {
        swap(str[l++], str[r++]);
        swap(str[l++], str[r]);
        r = r - 3;
    }
}

// function to conversion and print
// the hexadecimal value
void ipToHexa(int addr)
{
    char str[15];

    // convert integer to string for reverse
    sprintf(str, "0x%08x", addr);

    // reverse for get actual hexadecimal
    // number without reverse it will
    // print 0x0100007f for 127.0.0.1
    reverse(str);

    // print string
    cout << str << "\n";
}

// Driver code
int main()
{
    // The inet_addr() function  convert  string
    // in to standard IPv4 dotted decimal notation
    int addr = inet_addr("127.0.0.1");

    ipToHexa(addr);

    return 0;
}
Java
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;

public class Main {
    // Function to reverse hexadecimal number
    public static String reverse(String string) {
        // l for swap with index 2
        int l = 2;
        int r = string.length() - 2;

        // Convert string to char array for swapping
        char[] charArray = string.toCharArray();

        // Swap within two-2 pair
        while (l < r) {
            char temp = charArray[l];
            charArray[l] = charArray[r];
            charArray[r] = temp;
            l += 1;
            r -= 1;
            temp = charArray[l];
            charArray[l] = charArray[r];
            charArray[r] = temp;
            r -= 3;
        }

        // Convert char array back to string
        return new String(charArray);
    }

    // Function to conversion and print the hexadecimal value
    public static void ipToHexa(InetAddress addr) {
        // Convert IP address to byte array
        byte[] bytes = addr.getAddress();

        // Convert byte array to integer
        int ipAsInt = ByteBuffer.wrap(bytes).getInt();

        // Convert integer to hexadecimal string
        String string = "0x" + Integer.toHexString(ipAsInt);

        // Reverse to get actual hexadecimal number
        // Without reverse it will print 0x0100007f for 127.0.0.1
        string = reverse(string);

        // Print string
        System.out.println(string);
    }

    // Driver code
    public static void main(String[] args) throws UnknownHostException {
        // The getByName() function convert string into InetAddress
        InetAddress addr = InetAddress.getByName("127.0.0.1");

        ipToHexa(addr);
    }
}
JavaScript
// Importing required modules
const dns = require('dns');
const os = require('os');

// Function to reverse hexadecimal number
function reverse(string) {
    // l for swap with index 2
    let l = 2;
    let r = string.length - 2;

    // Convert string to char array for swapping
    let charArray = string.split('');

    // Swap within two-2 pair
    while (l < r) {
        let temp = charArray[l];
        charArray[l] = charArray[r];
        charArray[r] = temp;
        l += 1;
        r -= 1;
        temp = charArray[l];
        charArray[l] = charArray[r];
        charArray[r] = temp;
        r -= 3;
    }

    // Convert char array back to string
    return charArray.join('');
}

// Function to conversion and print the hexadecimal value
function ipToHexa(addr) {
    // Convert IP address to byte array
    let bytes = addr.split('.').map(function(item) {
        return parseInt(item, 10);
    });

    // Convert byte array to integer
    let ipAsInt = ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) >>> 0;

    // Convert integer to hexadecimal string
    let string = "0x" + ipAsInt.toString(16);

    // Reverse to get actual hexadecimal number
    // Without reverse it will print 0x0100007f for 127.0.0.1
    string = reverse(string);

    // Print string
    console.log(string);
}

// Driver code
dns.lookup(os.hostname(), function (err, addr, fam) {
    ipToHexa(addr);
});
Python3
import socket

# function for reverse hexadecimal number
def reverse(string):
    # l for swap with index 2
    l = 2
    r = len(string) - 2

    # swap with in two-2 pair
    while l < r:
        string[l], string[r] = string[r], string[l]
        l += 1
        r -= 1
        string[l], string[r] = string[r], string[l]
        r -= 3

# function to conversion and print
# the hexadecimal value
def ipToHexa(addr):
    # convert integer to string for reverse
    string = socket.inet_ntoa(addr.to_bytes(4, 'big'))
    string = '0x' + ''.join([format(int(x), '02x') for x in string.split('.')])

    # reverse for get actual hexadecimal
    # number without reverse it will
    # print 0x0100007f for 127.0.0.1
    string = list(string)
    reverse(string)
    string = ''.join(string)

    # print string
    print(string)

# Driver code
if __name__ == '__main__':
    # The inet_aton() function  convert  string
    # in to standard IPv4 dotted decimal notation
    addr = socket.inet_aton('127.0.0.1')

    ipToHexa(int.from_bytes(addr, 'big'))
# This code is contributed by Prajwal Kandekar

Output:

0x7f000001


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads