IP地址判斷有效性

來源:互聯網
上載者:User
#include "IPAddressValid.h"#include <stdio.h>#include <iostream>using namespace std;bool isOnePartValid(const char* cOnePartIPAddr, int len)//判斷一個欄位是不是合法{    if (NULL == cOnePartIPAddr || len <= 1)    {        return false;    }    if ('0' == cOnePartIPAddr[0] && 2 != len)//以0開頭的欄位不為0非法    {        return false;    }    int ipAddr =0;    int iCur = 0;    while ('\0' != cOnePartIPAddr[iCur])    {        if ('0'<= cOnePartIPAddr[iCur] && cOnePartIPAddr[iCur] <='9')        {            ipAddr = ipAddr*10 + cOnePartIPAddr[iCur]- '0';        }        else        {            return false;        }        iCur++;    }    if (ipAddr >= 0 && ipAddr <=255)    {        return true;    }    else    {        return false;    }}bool isIPAddressValid(const char* pszIPAddr){    // 請在此處實現    if (NULL == pszIPAddr)    {        return false;    }    int l = strlen(pszIPAddr);    if (l <7 || l > 15)    {        return false;    }    int iCur =0;    int iIpLen =0;    while (' ' == pszIPAddr[iCur])//去除前面空格    {        iCur++;        iIpLen++;    }    int begin = iCur;    while ('\0' != pszIPAddr[iCur])    {        iCur++;        iIpLen++;    }    int end = iIpLen;    for (int i = iIpLen-1 ; i >= begin; --i)//去除字串尾部的空格    {        if (' ' == pszIPAddr[i])        {            end--;        }        else        {            break;        }    }    char cOnePart[128];    int count = 0;    for (int i = begin; i <= end; i++)    {        memset(cOnePart, 0, sizeof(char) * 128);        int iOnePartCur =0;        int onePartLen =0;        while (i < end && '.' != pszIPAddr[i])        {            cOnePart[iOnePartCur] = pszIPAddr[i];            iOnePartCur++;            i++;            onePartLen++;        }        cOnePart[iOnePartCur] = '\0';        onePartLen++;        if (!isOnePartValid(cOnePart, onePartLen))        {            return false;        }        else        {            count ++;        }    }    if (4 == count )    {        return true;    }    else    {        return false;    }}int main(){    const char* pazIPAddress = "100.0.0.";    bool isIP = isIPAddressValid(pazIPAddress);    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.