首页 > 判断字符串是不是合法的IP地址?

判断字符串是不是合法的IP地址?

(09年亚信面试题)实现一个程序,对于给定的字符串,判断该字符串是不是一个合法的IP地址?

ps:要求不能用库,最好纯C手写


IPv4 Only

/\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/.test('127.0.0.1');

C 么... 之前在 StackOverflow 里看过一个

bool isValidIpAddress(char *ipAddress)
{
    struct sockaddr_in sa;
    int result = inet_pton(AF_INET, ipAddress, &(sa.sin_addr));
    return result != 0;
}

[1] http://stackoverflow.com/questions/79...


int isIPValid(char *ip ){
        int p[4] ={0,0,0,0};
        int len = strlen(ip);
        int j = 0;
        for(int i = 0; i < len; i++){
                if(ip[i] == '.' || i == len -1 ){
                        /*分割符*/
                        if(p[j] >= 0 && p[j] <= 255){
                                j ++;
                        }else{
                                return 0;
                        }
                }else{
                        int d = ip[i] - '0';
                        if(d > 9 || d < 0){
                                return 0;
                        }else{
                                p[j] = p[j] * 10 + d;
                        }
                }
        }
        return 1;
}

PHP 版 (IPv4 only)

if(!ip2long($ip)) echo "Invalid IP";
【热门文章】
【热门文章】