How do you validate that a string is a valid IPv4 address in C++?

前端 未结 17 2053
悲哀的现实
悲哀的现实 2020-12-04 23:21

I don\'t need to validate that the IP address is reachable or anything like that. I just want to validate that the string is in dotted-quad (xxx.xxx.xxx.xxx) IPv4 format, w

相关标签:
17条回答
  • 2020-12-05 00:02

    Boost.Asio provides the class ip::address. If you just want to verify the string, you can use it like this:

    std::string ipAddress = "127.0.0.1";
    boost::system::error_code ec;
    boost::asio::ip::address::from_string( ipAddress, ec );
    if ( ec )
        std::cerr << ec.message( ) << std::endl;
    

    This also works for hexadecimal and octal quads. This is also a much more portable solution.

    0 讨论(0)
  • 2020-12-05 00:02

    Here is the C program to validate a given IPV4 address. I have assumed that IP address is in decimal format. Please give me your thoughts on this.

      // strTokenFunction.cpp : Check if the specified address is a valid numeric IP address.
      // This function is equavalent to the IPAddress.TryParse() method in C#
    
    #include "stdafx.h"
    #include <stdio.h>
    #include <conio.h>
    #include <string.h>
    
    bool isValidIpAddress(char *st)
    {
        int num, i, len;
        char *ch;
    
        //counting number of quads present in a given IP address
        int quadsCnt=0;
    
        printf("Split IP: \"%s\"\n", st);
    
        len = strlen(st);
    
        //  Check if the string is valid
        if(len<7 || len>15)
            return false;
    
        ch = strtok(st, ".");
    
        while (ch != NULL) 
        {
            quadsCnt++;
            printf("Quald %d is %s\n", quadsCnt, ch);
    
            num = 0;
            i = 0;
    
            //  Get the current token and convert to an integer value
            while(ch[i]!='\0')
            {
                num = num*10;
                num = num+(ch[i]-'0');
                i++;
            }
    
            if(num<0 || num>255)
            {
                printf("Not a valid ip\n");
                return false;
            }
    
            if( (quadsCnt == 1 && num == 0) || (quadsCnt == 4 && num == 0))
            {
                printf("Not a valid ip, quad: %d AND/OR quad:%d is zero\n", quadsCnt, quadsCnt);
                return false;
            }
    
            ch = strtok(NULL, ".");
        }
    
        //  Check the address string, should be n.n.n.n format
        if(quadsCnt!=4)
        {
            return false;
        }
    
        //  Looks like a valid IP address
        return true;
    }
    
    int main() 
    {
        char st[] = "192.255.20.30";
        //char st[] = "255.255.255.255";
        //char st[] = "0.255.255.0";
    
        if(isValidIpAddress(st))
        {
            printf("The given IP is a valid IP address\n"); 
        }
        else
        {
            printf("The given IP is not a valid IP address\n");
        }
    }
    
    0 讨论(0)
  • 2020-12-05 00:04

    If you are on windows you can make use of WSAStringToAddress and based on the return value we know, if the passed argument is valid IP or not. This supports both IPv4 & IPv6 from Windows 2000 onwards.

    0 讨论(0)
  • 2020-12-05 00:04
    vector<string> &split(const string &s, char delim, vector<string> &elems) {
        stringstream ss(s);
        string item;
        while(getline(ss, item, delim)) {
           elems.push_back(item);
        }
        return elems;
    }
    
    vector<string> split(const string &s, char delim) {
       vector<string> elems;
       return split(s, delim, elems);
    }
    
    
    bool isIPAddress(string  ipaddr){
    
        if (ipaddr.length()){
                vector<string> _ip=split(ipaddr,'.');
                if (_ip.size()==4){
                        for (int i=0; i < 4; i++){
                                for (int j=0; j < _ip[i].length(); j++)
                                        if (!isdigit(_ip[i][j])) return false;
                                if ((atoi(_ip[i].c_str()) < 0) || (atoi(_ip[i].c_str()) > 255)) return false;
                        }
                return true;
                }
        }
        return false;
     }
    
    0 讨论(0)
  • 2020-12-05 00:07
    void validate_ip_address(const std::string& s) {
        const std::string number_0_255 = "((([0-9])|([1-9][0-9])|(1[0-9][0-9]|2[0-4][0-9]|25[0-5])){1})";
        const std::string dot = "(\\.){1}";
        static const boost::regex e(number_0_255 + dot + number_0_255 + dot + number_0_255 + dot + number_0_255);
        if (!regex_match(s, e)) {
            throw std::runtime_error(std::string("Uncorrect address IP: ") + s);
        }
    }
    
    0 讨论(0)
  • 2020-12-05 00:08

    I have done the same using only C stdlib functions altough it does not support octal quads as mentioned above, but that should not be an issue, I can easily add that part and give it to you. Being a beginner (student) I din't even know until now that it is possible to get an octal number within your ip. I thought it must be a decimal.

    0 讨论(0)
提交回复
热议问题