package provide Tools 1.0
namespace eval Valid {

##
## Check the argument. If it is an IP address, lookup the hostname, 
## else lookup the address.
##
proc nslook {arg} {
	package require Tnm
	
	set error [catch {Tnm::netdb hosts address $arg} res]
	
	if {$error} {
	    # dns will return the IP if the IP is sent as the arg AND the IP is associated with a name
	    set error [catch {Tnm::dns address $arg} res]
	    if {$res == $arg} {
		set error 1
	    }
	} else { return $res }
	
	if {$error} {
		set error [catch {Tnm::netdb hosts name $arg} res]
	} else { return $res }
	
	if {$error} {
		set error [catch {Tnm::dns name $arg} res]
	} else { return $res }
		
	if {$error} {
	    set res "failed"
    	}  
    	
    	return $res
}



proc IPnum {ip} {
	if { [info tclversion] < 8.1 } {
		return -code error "[namespace current]::IPnum requires tcl 8.1 or higher"
	}
	regexp {^([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])(\.([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){3}$} $ip
}

proc IPname {name} {
	if {![regexp {^([a-z]|[A-Z])} $name]} {
		# First character was not alpha
		return 0
	}
	if {[nslook $name] == "failed"} {
		return 0
	} else {
		return 1
	}
}
} ;# end namespace Valid