I want to validate an IP address and found this. Import doesn't seem to work so I tried just copy the code into Project Library https://github.com/python/cpython/blob/3.11/Lib/ipaddress.py but that doesn't seem to work either.
I'm guessing it is because this is 3.3 and ignition runs 2.7 python version.
Is there something that works in 2.7?
main function I am looking for is something that takes a string and verifies it is a valid IP address IPV4.
Generally, you'd pass whatever you have to java.net.InetAddress.getByName()
, and then check if you got an instance of Inet4Address
. As a side benefit, it will look up a provided hostname, too.
2 Likes
import java
ipaddress = "162.2.2.999"
try:
java.net.InetAddress.getByName(ipaddress)
except:
print "no good"
else:
print "good"
looks like that works. Thanks.
lrose
August 14, 2023, 3:57pm
5
Holy Moly, don't do that. You're importing all of the java "name space".
Like this:
from java.net import InetAddress
ipaddress = '162.2.2.999'
try:
InetAddress.getByName(ipaddress)
print 'good'
except:
print 'no good'
1 Like
Uhm, you said you wanted to check for an IPv4 address. The above will allow IPv6 addresses. Use this:
from java.net import InetAddress, Inet4Address
ipaddress = '162.2.2.999'
try:
addr = InetAddress.getByName(ipaddress)
if isinstance(addr, Inet4Address):
print 'good'
else:
print 'not IPv4'
except:
print 'no good'
4 Likes