Search code examples
python-3.xtypesip-addresssocks

Python 3 Convert IPV4Address to string


I am attempting to convert an IPV4Address in python3 to a string or int as per the error message below. I'm not quite sure I'm doing wrong here. I also tried int(x) and bytes(x) neither work

Traceback (most recent call last):
  File "/Users/krisarmstrong/PycharmProjects/pyportscanner/pyportscanner", line 113, in <module>
main()
  File "/Users/krisarmstrong/PycharmProjects/pyportscanner/pyportscanner", line 105, in main
get_ip_address()
   File "/Users/krisarmstrong/PycharmProjects/pyportscanner/pyportscanner", line 70, in get_ip_address
result = sock.connect_ex((x, port))
TypeError: str, bytes or bytearray expected, not IPv4Address

My code is as follows:

def get_ip_address():
ip_address_list = []
port = '2359'
network = ipaddress.ip_network('10.0.16.0/20')
for x in network.hosts():
    str(x)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex((x, port))
    if result == 0:
        print("Port"), port(" Open")
    sock.close()
    ip_address_list.append(x)
return ip_address_list

Solution

  • In your code snippet (relevant lines below), the str(x) line returns x as a string but does store this string in x. You need to do x = str(x) to store the string representation in x (or just use str(x) in place of x when calling connect_ex).

    for x in network.hosts():
        str(x)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((x, port))