# coding=utf-8
'''
DATE: 2020/09/08
AUTHOR: Yanxi Li
8-2 使用Python实现端口扫描
'''

"""
扫描原理：
1.参数接收
    参数值为要扫描的目标机器IP和端口
2.发送和收取相应包
3.包内容判断

如果要构造TCP请求包
在Python里主要使用的模块为socket和scapy

method 1: socket有一个connect的方法，直接可以对目标IP和端口进行连接尝试并返回结果，无需自己去构建SYN包

python3 port_scan_socket.py 10.0.4.141 22  

"""

import sys
import socket

socket.setdefaulttimeout(0.5)


def scan(ip, port):
    print("Server %s, Port: %s is scaning" % (ip, port))
    try:
        port = int(port)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # socket.AF_INET 服务间通信      socket.SOCK_STREAM 流式socket，for TCP
        res = sock.connect_ex((ip, port))
        print(res)
        if res == 0:
            print("Result: OPEN")
        else:
            print("Result: CLOSE")
        sock.close()
    except socket.gaierror:
        print("Hostname could not be resolved. Exiting...")
    except socket.error:
        print("Can't connect to the server...")


if __name__ == '__main__':
    ip = sys.argv[1]
    port = sys.argv[2]
    scan(ip, port)
