TCP客户端
import socket
target_host = "www.baidu.com"
target_port = 80
# 建立一个socket
# AF_INET:使用IPv4地址或主机名,SOCK_STREAM:使用TCP
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接客户端
client.connect((target_host, target_port))
# 发送一些数据
client.send("GET / HTTP/1.1\r\nHost: baidu.com\r\n\r\n")
# 接收一些数据
response = client.recv(4096)
print response
UDP客户端
import socket
target_host = "127.0.0.1"
target_port = 80
# 建立一个socket对象
# SOCK_DGRAM:使用UDP
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 发送数据
client.sendto("aabbcc", (target_host, target_port))
# 接收数据
data, addr = client.recvfrom(4096)
print data
TCP服务器
import socket
import threading
bind_ip = "0.0.0.0"
bind_port = 5000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 监听地址和端口
server.bind((bind_ip, bind_port))
# 最大连接数为5
server.listen(5)
print "[*] Listening on %s:%d" %(bind_ip, bind_port)
# 客户端处理线程
def handle_client(client_socket):
# 打印客户端接收内容
request = client_socket.recv(1024)
print "[*] Reveived: %s" %request
# 返还一个数据包
client_socket.send("ACK!")
client_socket.close()
while True:
# client:接收到的客户端套接字,addr:远程连接细节,ip:port
client, addr = server.accept()
print "[*] Accepted connection from: %s:%d" %(addr[0], addr[1])
# 挂起客户端线程,处理传入的数据
client_hander = threading.Thread(target=handle_client, args=(client,);
client_hander.start()
将之前的TCP客户端改一下
target_host = "127.0.0.1"
target_port = 5000
参考
Python 黑帽子 黑客与渗透编程之道