谁能告诉我如何验证IP地址 [英] Can anyone tell me how to validate ip address

查看:118
本文介绍了谁能告诉我如何验证IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我如何验证我作为TCHAR的IP地址.
验证功能来验证IP地址.
例如它应包含3个点(.),并且值应在1到225之间.

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.

推荐答案

我强烈建议从 boost 为您做到这一点;但是如果您决定手动滚动,下面是如何实现的细分示例;

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;

#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;
}



请注意,如果您使用的是 UNICODE 平台,则必须将其更改为std::wstring,某些#ifdef应该可以解决问题.

希望这会有所帮助,
弗雷德里克(Fredrik)



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


这篇关于谁能告诉我如何验证IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆