C program to format/extract ip address octets

This program will read IP address from user in string format, and extract each octet from the given user input. User input must be in xxx.xxx.xxx.xxx format. An IP address has four octets and using this program we will extract given octets in string format to an integer format.

Extract Octets from Ip/ Fomrat Ip address from string using C program

/*C program to format/extract ip address octets.*/

#include <stdio.h>
#include <string.h>

/*
Function : extractIpAddress
Arguments : 
1) sourceString - String pointer that contains ip address
2) ipAddress - Target variable short type array pointer that will store ip address octets
*/
void extractIpAddress(unsigned char* sourceString, short* ipAddress)
{
    unsigned short len = 0;
    unsigned char oct[4] = { 0 }, cnt = 0, cnt1 = 0, i, buf[5];

    len = strlen(sourceString);
    for (i = 0; i < len; i++) {
        if (sourceString[i] != '.') {
            buf[cnt++] = sourceString[i];
        }
        if (sourceString[i] == '.' || i == len - 1) {
            buf[cnt] = '\0';
            cnt = 0;
            oct[cnt1++] = atoi(buf);
        }
    }
    ipAddress[0] = oct[0];
    ipAddress[1] = oct[1];
    ipAddress[2] = oct[2];
    ipAddress[3] = oct[3];
}

int main()
{
    unsigned char ip[] = { 0 };
    short ipAddress[4];

    printf("Enter IP Address (xxx.xxx.xxx.xxx format): ");
    gets(ip);

    extractIpAddress(ip, &ipAddress[0]);

    printf("\nIp Address: %03d. %03d. %03d. %03d\n", ipAddress[0], ipAddress[1], ipAddress[2], ipAddress[3]);

    return 0;
}

Output:

Enter IP Address (xxx.xxx.xxx.xxx format): 167.78.190.091 

Ip Address: 167. 078. 190. 091

C Advance Programs »



Related Programs

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.