Szarny.io

There should be one-- and preferably only one --obvious way to do it.

python2でのTCPサーバとクライアントの作成

TCP Serverのソースコード

import socket 
import threading 

SERVER_IP = "0.0.0.0" 
SERVER_PORT = 8080 

# Create socket object (AF_INET -> IPv4 , SOCK_STREAM -> TCP) 
s_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# Binding ip and port 
s_sock.bind((SERVER_IP, SERVER_PORT)) 

# Number of connection queue 
s_sock.listen(5) 

print "[*] Server listening | %s:%d" % (SERVER_IP,SERVER_PORT) 

def client_handler(c_sock): 
req = c_sock.recv(4096) 
print "[*] Request | %s" % req 

res = "Server ACK" 
c_sock.send(res) 
print "[*] Response | %s" % res 

c_sock.close() 

while True: 
client,addr = s_sock.accept() 
print "[*] Connection | %s:%d" % (addr[0],addr[1]) 

client_handler_thread = threading.Thread(target=client_handler, args=(client,)) 
client_handler_thread.start()

TCP Clientのソースコード

import socket

host = "0.0.0.0"
port = 8080

# Create socket object
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Establish TCP connection
client.connect((host, port))

# Data send
client.send("HELLO")

# Data receive
data = client.recv(4096)

print data

実験

Client側

root@kali:~/Desktop# python2 tcp_client.py
Server ACK
root@kali:~/Desktop# python2 tcp_client.py
Server ACK
root@kali:~/Desktop# python2 tcp_client.py
Server ACK

Server側

[*] Server listening | 0.0.0.0:8080
[*] Connection | 127.0.0.1:41096
[*] Request | HELLO
[*] Response | Server ACK
[*] Connection | 127.0.0.1:41098
[*] Request | HELLO
[*] Response | Server ACK
[*] Connection | 127.0.0.1:41100
[*] Request | HELLO
[*] Response | Server ACK

参考書籍

サイバーセキュリティプログラミング ―Pythonで学ぶハッカーの思考

サイバーセキュリティプログラミング ―Pythonで学ぶハッカーの思考