Sharpen Python skills in the field of cybersecurity.
讓在資安領域我們磨利Python技術。
Let's get started! 開始吧!
⭐ 可以查看上一篇教學
⭐ 如果你想知道什麼是字母'b'代表的意思 | StackOverflow
sendto()
: 代表傳送資料到伺服器connect()
recvfrom()
: 接收回傳資料#udp_client.py
import socket
HOST = "127.0.0.1"
PORT = 9997
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b"AAABBBCCC",(HOST, PORT))
data, addr = client.recvfrom(4096)
print(data.decode())
client.close()
⭐ 例子來自 Real Python
來看看到底伺服器和客戶端如何運作。
這個伺服器將回聲任何接收到的資料
# echo-client.py
import socket
HOST = "127.0.0.1" # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello, world")
data = s.recv(1024)
print(f"Received {data!r}")
# echo_server.py
import socket
HOST = "127.0.0.1" # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
先跑伺服器,再跑客戶端。
Hooray!
Reference參考資料