如何检测 输入的 ip 地址是否合法,在后台?
用正则表达式?
thanks!

解决方案 »

  1.   

    用正则比较麻烦,因为还要小于255.
    直接用.分成数组,判断每个元素>=0 且<= 255就可。
      

  2.   

    function IP2V(ip)
    {
     re=/(\d+)\.(\d+)\.(\d+)\.(\d+)/g  //匹配IP地址的正则表达式
    if(re.test(ip))
    {
    return RegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1
    }
    else
    {
     throw new Error("不是一个正确的IP地址!")
    }
    }
      

  3.   

    (?<Num1>\d+)\.(?<Num2>\d+)\.(?<Num3>\d+)\.(?<Num4>\d+$)Regex regex = new Regex(@"(?<Num1>\d+)\.(?<Num2>\d+)\.(?<Num3>\d+)\.(?<Num4>\d+$)");
    Match m = regex.Match("192.168.1.58");
    string[] gn = regex.GetGroupNames();
    if(m.Success) {
    MessageBox.Show(m.Groups["Num1"].Value);
    }
    你可以看看正则表达式中各个符号的意思。 在这里你查看gn你就知道了。
      

  4.   

    Regex regex = new Regex(@"(?<Num1>\d+)\.(?<Num2>\d+)\.(?<Num3>\d+)\.(?<Num4>\d+$)");
    Match m = regex.Match("192.168.1.58");
    string[] gn = regex.GetGroupNames();
    if(m.Success) {
    // check num1 ---num4 whether between 0 to 255
    if(Convert.ToInt32(m.Groups["Num1"].Value) <0 || Convert.ToInt32(m.Groups["Num1"].Value) >255 ...) {
    return false;
    }
    }
      

  5.   

    Click the link to solve your problem.Good luck!