Decided to add an IPV4 and IPV6 address validator, and clean up the code.
-- Get IP address (IPV4, or IPV6) from user, validate it, and determine if the connection
-- can be made with ping or ping6. Report [un]successful.
-- Added IP address validator
-- Revision 2.0, Tested: El Capitan 10.11.6, Python 2.7.10 (OS X)
-- VikingOSX, 2017-04-07, Apple Support Communities
use scripting additions
set ip_dialog to "Enter the IP Address" & return & return & ¬
"IPV4 Format: nn.nn.nn.nn (as Integers)" & return & ¬
"IPV6 Format: nnnn:nnnn:nnnn:nnnn:: (as hexadecimal values)" & return & ¬
"IPV6 Format: nnnn:nnnn:nnnn:nnnn:nnnn:nnnn:nnnn:nnnn: (long form)"
set ip_address to ""
set ip_address to text returned of (display dialogip_dialogdefault answer "" with title "Ping")
-- log ip_address
set ret to validate_ip(ip_address) as boolean
if not ret then
display alert "Invalid IP Address" messageip_addressascriticalgiving up after 10
return
end if
try
if ip_address contains "." then
set ping to (do shell script "ping -c2 " & ip_address)
else if ip_address contains ":" then
set ping to (do shell script "ping6 -c2 " & ip_address)
end if
display dialog "Connection Successful"
on error errmsgnumbererrnbr
display dialog "Connection Unsuccessful"
my error_handler(errnbr, errmsg)
end try
return
on validate_ip(addrStr)
return do shell script "python <<'EOF' - " & addrStr & "
#!/usr/bin/python
# coding: utf-8
import socket
import sys
try:
addr = ''.join(sys.argv[1])
if addr.count('.') == 3 and socket.inet_pton(socket.AF_INET, addr):
print(True)
elif addr.count(':') >= 4 and socket.inet_pton(socket.AF_INET6, addr):
print(True)
else:
print(False)
except socket.error:
print(False)
EOF"
end validate_ip
on error_handler(nbr, msg)
return display alert "[ " & nbr & " ] " & msg as critical giving up after 10
end error_handler