tcp client.py
import socket
target_host="127.0.0.1"
target_port=81
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((target_host,target_port))
client.send("hello".encode("utf-8"))
reponse=client.recv(4096)
print(reponse)
tcp server.py
import socket
import threading
bind_ip="127.0.0.1"
bind_port=81
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((bind_ip,bind_port))
server.listen(5)
print("[*] Listening on %s:%d" % (bind_ip,bind_port))
def handle_client(client_socket):
request=client_socket.recv(1024)
print("[*] Received: %s" % request)
client_socket.send("ack!".encode("utf-8"))
client_socket.close()
while(True):
client,addr=server.accept()
print("[*] Accept connection from %s:%d" % (addr[0],addr[1]))
client_handler=threading.Thread(target=handle_client,args=(client,))
client_handler.start()
效果:首先运行tcp server.py,然后多次运行tcp client.py,则tcp server.py对应的命令行会接受到如下内容
[*] Listening on 127.0.0.1:81
[*] Accept connection from 127.0.0.1:20929
[*] Received: b'hello'
[*] Accept connection from 127.0.0.1:20931
[*] Received: b'hello'
[*] Accept connection from 127.0.0.1:20932
[*] Received: b'hello'
[*] Accept connection from 127.0.0.1:20933
[*] Received: b'hello'
......
tcp client.py对应的命令行会接受到如下内容
b'ack!'
用处:DOS下的netcat命令可以用于连接服务器,但由于其能力强,因此容易被独立网络的管理人员禁止。但上述代码中使用到的socket模块却与python绑定,因此外部人员进入内部网络后,可以使用python手动实现一个tcp协议的客户端,将网络中的一个IP端口开放,并通过外部的服务端来向客户端发送信息,从而达到构建数据连接的作用。
网友评论