Whois client for Python
(ip_address)
| 3522 | |
| 3523 | |
| 3524 | def whois(ip_address): |
| 3525 | # type: (str) -> bytes |
| 3526 | """Whois client for Python""" |
| 3527 | whois_ip = str(ip_address) |
| 3528 | try: |
| 3529 | query = socket.gethostbyname(whois_ip) |
| 3530 | except Exception: |
| 3531 | query = whois_ip |
| 3532 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 3533 | s.connect(("whois.ripe.net", 43)) |
| 3534 | s.send(query.encode("utf8") + b"\r\n") |
| 3535 | answer = b"" |
| 3536 | while True: |
| 3537 | d = s.recv(4096) |
| 3538 | answer += d |
| 3539 | if not d: |
| 3540 | break |
| 3541 | s.close() |
| 3542 | ignore_tag = b"remarks:" |
| 3543 | # ignore all lines starting with the ignore_tag |
| 3544 | lines = [line for line in answer.split(b"\n") if not line or (line and not line.startswith(ignore_tag))] # noqa: E501 |
| 3545 | # remove empty lines at the bottom |
| 3546 | for i in range(1, len(lines)): |
| 3547 | if not lines[-i].strip(): |
| 3548 | del lines[-i] |
| 3549 | else: |
| 3550 | break |
| 3551 | return b"\n".join(lines[3:]) |
| 3552 | |
| 3553 | #################### |
| 3554 | # CLI utils # |