Coding Practice

Write a C program to convert IP address to 32-bit binary format

Convert IP Address to 32-bit Binary Format

1. Write a C program that takes a classless IP address as input and displays it in binary, the number of network and host address depending on number represented after the backslash

Classless is called Classless Inter-Domain Routing. It was introduced in 1993 to replace classfull addressing and it allows the user to use Variable Length Subnet Makss(VLSM). Class-less subnet masks are denoted by /X. X is the subnet mask. For example 192.168.0.1/24.
[Note: Input must be like this XXX.XXX.XXX.XXX/XX
Example: 192.168.0.1/24]
Network Address: (224-2)
Host Address: (28-2)

Sample Output
Enter IPv4: 192.168.0.1/24
IP in binary: 11000000.10101000.00000000.00000001
Network address: (2^24)-2 = 16777214
Host Address: (2^8)-2 = 254


Process returned 29 (0x1D)   execution time : 19.943 s
Press any key to continue.
Source Code
#include<stdio.h>
#include<math.h>

void decToBin(int number)
{
    int i, bin[8];

    for(i = 0; number > 0; i++)
    {
        bin[i] = number % 2;
        number = number/2;
    }
    for(i = i-1; i >= 0; i--)
    {
        number = (10 * number) + bin[i];
    }
    printf("%0.8d", number);
}

void main()
{
    int i, count = 0, ipv4Len, number = 0, digit, netMask = 0, inputLen;
    long netAddress, hostAddress;
    char ip[30];

    printf("Enter IPv4: ");
    scanf("%s", ip);

    for(i = 0; ip[i] != 47; i++);
    ipv4Len = i;
    for(i = ipv4Len+1; ip[i] != '\0'; i++);
    inputLen = i;

    printf("IP in binary: ");
    for(i = 0; i < ipv4Len; i++)
    {
        if(ip[i] == '.')
        {
            decToBin(number);
            number = 0;
            printf(".");
        }
        else
        {
            digit = ip[i] - '0';
            number = (10 * number) + digit;
        }
    }
    decToBin(number);

    for(i = ipv4Len+1; i < inputLen; i++)
    {
        //ch = '8' = 56, '0' = 48, digit = ch - '0'
        digit = ip[i] - '0';
        netMask = (10 * netMask) + digit;
    }
    netAddress = pow(2, netMask);
    hostAddress = pow(2, (32-netMask));

    printf("\nNetwork address: (2^%d)-2 = %ld\n", netMask, (netAddress-2));
    printf("Host Address: (2^%d)-2 = %ld\n\n", (32-netMask), (hostAddress-2));
}
Sample Output
Enter IPv4: 103.237.76.98/16
IP in binary: 01100111.11101101.01001100.01100010
Network address: (2^16)-2 = 65534
Host Address: (2^16)-2 = 65534


Process returned 32 (0x20)   execution time : 43.430 s
Press any key to continue.
Change Theme
X