使用tcl验证ip-address

时间:2012-05-17 09:45:34

标签: tcl

你好frnds m面对这个程序中的问题..任何告诉我在哪里犯错? 我能够验证255.255.255.255 IP地址

puts "Enter a valid ip address:"
set string [gets stdin]
if {[regexp {^([1-9]|[1]\d{2}|[2][0-4]\d|25[0-5])((\.\d{0,2}|1\d{2}|2[0-4]\d|25[0-5]){3})$} $string match]} {
    puts $string
} else {
    puts "INVALID-ADDRESS"
}

7 个答案:

答案 0 :(得分:5)

不要重新发明轮子。有许多有关如何验证IP地址的工作示例。请参阅此处了解http://wiki.tcl.tk/989

此外,如果你有TCLlib,你可以使用 :: ip :: version 命令,例如

% package require ip
1.2
% ::ip::version 192.168.0.1
4
% ::ip::version www.google.com
-1
% ::ip::version 192.168.0.333
-1

答案 1 :(得分:2)

set ip "1.2.3.4"
if { [ catch[regexp {(\d+)\.(\d+)\.(\d+)\.(\d+)} $ip man]] } {
    set flag 0
}
set cut [split $ip "."]
set flag "" 
if {[llength $cut] == 4} {
    set flag 1
} else {
    set flag 0 
}
if {[lindex $cut 0] == 0} { 
    set flag  0 
}
foreach nut $cut {
    if {[string length $nut] > 3} {
        set flag 0
    }
    if {$nut > 255} {
        set flag 0 
    }
    set a [split $nut ""]
    if { [lindex $a 0] == 0 } {
        set flag 0
    }
    #set int [lappend mat $nut]
}
if {$flag == 0} { 
    puts "Not a valid IP"
} else {
    puts "IP IS VALID:$man"
}

答案 2 :(得分:1)

proc validateIP {IP} {
    if {[regexp {^(?:(\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))(?:\.((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))){3}$} $IP]} {
        puts "$IP is a valid IP"
    } else {
        puts "INVALID-ADDRESS"
    }
}

你的正则表达式有一些错误,特别是点的放置只与第一种可能性分组

答案 3 :(得分:1)

我只是为初学者提供最简单的模式。

pattern: /^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/

答案 4 :(得分:1)

% set ip "192.168.123.23"
192.168.123.23
% regexp {([0-9]+\.)([0-9]+\.)([0-9]+\.)([0-9]+)} $ip match a b c d
1
% if {$a <= 255 & $b <= 255 & $c <= 255 & $d <= 255} {
  puts "this is a valid ip address"
  } else {
  puts "this not a valid ip address"
 }

这是一个有效的IP地址

答案 5 :(得分:0)

puts "enter your ip address"
set ip [gets stdin]
regexp {([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)} "$ip" match 1st 2nd 3rd 4rth

if {$1st < 256 & $2nd < 256 & $3rd <256 & $4rth<256} { // numbers in range?
  puts "valid IP address"
} else { 
  puts "not valid IP address"
}

答案 6 :(得分:0)

set ip 100.12.230.250

set mat [regexp -nocase {(([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$} $ip match]


if {$mat == 1} {
    puts "Valid Ip"
} else {
   puts "Invalid Ip"
}