Python Socket communication sample. The data transmission itself can be written in a minimum of two lines.
with socket.socket(socket.AF_INET, args.p) as nsocket:
#Connect only for TCP
if args.p is socket.SOCK_STREAM:
nsocket.connect((host, port))
#Data transmission
nsocket.send(data)
An nc command-like, simple data throwing tool with parameters added. Scheduled to be expanded.
import argparse
import socket
#Parameter processing
parser = argparse.ArgumentParser()
parser.add_argument("-p", default=socket.SOCK_STREAM, help="Potocol TCP or UDP")
parser.add_argument("host", help="Hostname or IP Address")
parser.add_argument("port", help="Port number")
parser.add_argument("-m", default='0123456789abcdef' , help="Send data")
parser.add_argument("-f", type=argparse.FileType('rb'), help="Send data from a file")
args = parser.parse_args()
send_data = '0123456789abcdef'
if args.m:
send_data = args.m.encode()
if args.f:
send_data = args.f.read()
#Actual communication
with socket.socket(socket.AF_INET, args.p) as nsocket:
#Connect only for TCP
if args.p is socket.SOCK_STREAM:
nsocket.connect((args.host, int(args.port)))
#Data transmission
nsocket.send(send_data)
"""
#Receive response
nsocket.settimeout(3)
data = nsocket.recv(1024)
print(repr(data))
"""
Recommended Posts