Click here to Skip to main content
15,887,361 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Can anyone tell me how to validate ip address which i have taken as TCHAR.
validation function to validate ip address.
such as it should contain 3 dots(.) and value should be in the range of 1 to 225.
Posted
Comments
Uday P.Singh 13-Mar-12 15:33pm    
do you want it in Javascript, C# or what?
amityadav4a 13-Mar-12 15:39pm    
i want it in c++. Have write code to accept ip address and ip mask and i want to validate it.
Sergey Alexandrovich Kryukov 13-Mar-12 18:15pm    
What do you want to validate, exactly: just right string format (which is easy, I don't even understand what to ask about) or something related to it semantic: network class, availability of the host with such IP or something?

Anyway, IPv6, IPv4 or both? Do you need to classify the addresses into such?
--SA
amityadav4a 13-Mar-12 23:41pm    
Ipv4.
'Just want that user should enter ip in the range 0.0.0.0 to 225.225.225.255 and not any character or special symbol or wrong ip

1 solution

I'd highly recommend getting something from boost to do this for you; but if you've decided to hand-roll it, here's a broken down example of how it can be achieved;

C++
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>

using namespace std;

// You won't need this
typedef char TCHAR;

vector<string> split(TCHAR* str, TCHAR delimiter)
{
    const string data(str);
    vector<string> elements;

    string element;
    for(int i = 0; i < data.size(); ++i)
    {
        if (data[i] == delimiter)
        {
            elements.push_back(element);
            element.clear();
        }
        else
            element += data[i];
    }
    elements.push_back(element);
    return elements;
}

bool toInt(const string& str, int* result)
{
    if (str.find_first_not_of("0123456789") != string::npos)
        return false;

    stringstream stream(str);
    stream >> *result; // Should probably check the return value here
    return true;
}

bool validate(TCHAR* ip)
{
    const static TCHAR delimiter = '.';
    const vector<string> parts = split(ip, delimiter);
    if (parts.size() != 4)
        return false;

    for(int i = 0; i < parts.size(); ++i)
    {
        int part;
        if (!toInt(parts[i], &part))
            return false;
        if (part < 0 || part > 255)
            return false;
    }
    return true;
}

int main()
{
    cout << validate("13.23.12.221") << endl;
    return 0;
}


Note that you have to change it to std::wstring if you're on a UNICODE platform, some sort of #ifdef should do the trick.

Hope this helps,
Fredrik
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900