Socket.gaierror: [Errno -2]

I couldn’t figured out what when wrong with the target. I gave it a random hostname, and not IP address, but still nothing.
Edit: Still not fully resolve, but apparently, if the 2nd argument is a number, and without any letter, then it work. I…don’t know why the 2nd argument can only be number(s).

python3 scanner.py sad7a7dsa7d    
Traceback (most recent call last):
  File "/home/kali/python/scanner.py", line 9, in <module>
    target = socket.gethostbyname(sys.argv[1])
socket.gaierror: [Errno -2] Name or service not known
import sys
import socket
from datetime import datetime

if len(sys.argv) == 2:
	target = socket.gethostbyname(sys.argv[1])
else:
	print("Invalid amount of agruments")
	print("syntax: python3 scanner.py <ip>")

Hello.
I am not a python expert, but personally this topic is interesting to me. Thanks for sharing this!

The python documentation says:

If the host name is an IPv4 address itself it is returned unchanged.

Following the explanation above, I think that if the argument is a number, it is converted directly to the corresponding IP address and no error occurs.

Edit: Still not fully resolve, but apparently, if the 2nd argument is a number, and without any letter, then it work. I…don’t know why the 2nd argument can only be number(s).

Here is my example.

Python 3.9.2 (default, Jun  7 2022, 22:07:24)
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket

# 1st. The same argument "sad7a7dsa7d" but this host does not exist, 
# so an exception is returned.
>>> target = socket.gethostbyname("sad7a7dsa7d")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.gaierror: [Errno 8] nodename nor servname provided, or not known

# 2nd. Pass the argument  as a numeric string. exp. 123
# It is then converted as an ip address with the same value.
>>> target = socket.gethostbyname("123")
>>> target
'0.0.0.123'

# 3ed. Pass the argument  as a numeric string. exp. 256
>>> target = socket.gethostbyname("256")
>>> target
'0.0.1.0'

# 4th. Pass the argument  "freecodecamp.org"
>>> target = socket.gethostbyname("freecodecamp.org")

# The expected IP address is returned without exception......

I hope I could be of some help.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.