代码之家  ›  专栏  ›  技术社区  ›  Codieroot

扫描ip地址的端口并使用python打印响应状态

  •  0
  • Codieroot  · 技术社区  · 7 年前

    我正在尝试访问IP地址的端口并打印 status code (即 200 OK , 502 Bad Gateway 等等)。假设,假设 port 80 在ip地址打开 xx.xx.xx.xxx . 所以 xx.xx.xx.xxx:80 应该给我们 200 OK . 在我的代码中,我使用的是端口 811450 ,它肯定没有打开,也没有运行任何应用程序。但它没有显示任何错误。

    import httplib  
    import urllib
    import socket
    
    
    class mysocket:
    
    
        def __init__(self, sock=None):
            if sock is None:
                self.sock = socket.socket(
                    socket.AF_INET, socket.SOCK_STREAM)
            else:
                self.sock = sock
    
        host = "xx.xx.xx.xxx"
        port = "811450"
    
        def connect(self, host, port):
            self.sock.connect((host, port))
    
        def mysend(self, msg):
            totalsent = 0
            while totalsent < MSGLEN:
                sent = self.sock.send(msg[totalsent:])
                if sent == 0:
                    raise RuntimeError("socket connection broken")
                totalsent = totalsent + sent
    
        def myreceive(self):
            chunks = []
            bytes_recd = 0
            while bytes_recd < MSGLEN:
                chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048))
                if chunk == '':
                    raise RuntimeError("socket connection broken")
                chunks.append(chunk)
                bytes_recd = bytes_recd + len(chunk)
            return ''.join(chunks)
    

    建议的实现方法是什么。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Erik Cederstrand    7 年前

    首先,811450不是有效的端口。最大有效TCP端口范围为65535。

    其次,您将TCP协议和HTTP协议混为一谈。如果希望从套接字获得HTTP响应,则需要发送有效的HTTP请求。您可以使用 requests 包裹:

    import requests
    
    r = requests.get('http://xx.xx.xx.xxx:811450')
    print(r.status_code)