LoginSignup
2
2

More than 3 years have passed since last update.

Python Socket通信サンプル/簡易データ投げ込みツール

Last updated at Posted at 2020-07-10

Socket通信サンプル

PythonのSocket通信サンプル。
データの送信自体は最小2行で書ける。

with socket.socket(socket.AF_INET, args.p) as nsocket:
    # TCPの場合のみconnect
    if args.p is socket.SOCK_STREAM:
        nsocket.connect((host, port))
    # データ送信
    nsocket.send(data)

簡易データ投げ込みツール

パラメータを加えたncコマンド風、簡易データ投げ込みツール。
拡張予定。

import argparse
import socket

# パラメータ処理
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()

# 実際の通信
with socket.socket(socket.AF_INET, args.p) as nsocket:
    # TCPの場合のみconnect
    if args.p is socket.SOCK_STREAM:
        nsocket.connect((args.host, int(args.port)))
    # データ送信
    nsocket.send(send_data)
"""
    # 応答受信
    nsocket.settimeout(3)
    data = nsocket.recv(1024)

    print(repr(data))
"""
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2