0

I am creating a basic "whois" script, but it is not working. When I try to run it in the Linux terminal, it returns the error:

"TypeError: a bytes-like object is required, not 'str'" indicated in the line of code: s.send(sys.argv[1]+"\r"+"\n").

consulta.py

#!/usr/share/python
import socket
import sys
import pyfiglet

ascii_banner = pyfiglet.figlet_format("WHOIS - Gustang")
print (ascii_banner)

reg = "whois.godaddy.com"

if len(sys.argv) == 2:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((reg, 43))
        s.send(sys.argv[1]+"\r"+"\n")
        resp = s.recv(1024)
        print (resp)
else:
        print ("Modo de Uso: IPv4 + Porta")
        print ("Exemplo: 255.255.255.255 21")
Nic3500
  • 8,144
  • 10
  • 29
  • 40
Gustang
  • 21
  • 2
  • 1
    Does this answer your question? [Python sockets error TypeError: a bytes-like object is required, not 'str' with send function](https://stackoverflow.com/questions/42612002/python-sockets-error-typeerror-a-bytes-like-object-is-required-not-str-with) – John Bollinger May 31 '23 at 16:52
  • Did you check the documentation? https://docs.python.org/3/library/socket.html – DarkKnight May 31 '23 at 16:58
  • Not related to the main problem, but `if len(sys.argv) == 2` should be `if len(sys.argv) == 3` for the given example. Also when given an example, better give the full program call such as `print ("Exemplo:\n\t./consulta.py 255.255.255.255 21")`. – Jardel Lucca May 31 '23 at 17:26

1 Answers1

0

You need to send bytes. The response will also be bytes.

With irrelevant parts of the code removed...

from socket import socket, AF_INET, SOCK_STREAM
from sys import argv

HOST = 'whois.godaddy.com'
PORT = 43
CONNECTION = HOST, PORT
CRLF = b'\r\n'
BUFSIZ = 16

def get_response(s: socket) -> str:
    ba = bytearray()
    while True:
        ba.extend(s.recv(BUFSIZ))
        if ba.endswith(CRLF):
            break
    return ba.decode()

if len(argv) == 2:
    with socket(AF_INET, SOCK_STREAM) as s:
        s.connect(CONNECTION)
        s.send(f'{argv[1]}\r\n'.encode())
        print(get_response(s))
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • Thank you very much for the corrections. Can you explain this part better: "CRLF = b'\r\n' BUFSIZ = 16 def get_response(s: socket) -> str: ba = bytearray() while True: ba.extend(s.recv(BUFSIZ)) if ba.endswith(CRLF): break return ba.decode()" – Gustang May 31 '23 at 18:02
  • @Gustang It would be quite difficult to offer you tutoring via stack**overflow** comments. There are many free resources for learning Python. Start here: https://www.python.org/about/gettingstarted/ – DarkKnight Jun 01 '23 at 06:26