LoginSignup
1
2

More than 5 years have passed since last update.

Python > UDP > UDP送信して応答を受ける > netcatとsubprocess使用

Last updated at Posted at 2018-04-20
動作環境
CentOS 6.9 (64bit)
Python 3.4.5

処理概要

  • UDP送信する
  • UDP応答を受信する
  • socketを使わない
    • 深い意味があるわけではない
  • 受信タイムアウト: 1秒

code v0.1

udp_send_recv_180420.py
import subprocess as sb

'''
v0.1 Apr. 20, 2018
  - add send_recv()
'''

# on CentOS 6.9 (Final)
# on Python 3.4.5


def send_recv(ipadr, udpport, msg):
    acmd = 'echo "%s" | nc -u %s %s -w 1' % (msg, ipadr, udpport)
    return sb.getoutput(acmd)

IPADR = "192.168.0.7"
UDPPORT = 7000

for loop in range(3):
    res = send_recv(IPADR, UDPPORT, msg="TEST2")
    print(res)

相手側

IPアドレス: 192.168.0.7

受信内容を返信するエコーサーバーを動かしておく。

結果

$ python3 udp_send_recv_180420.py 
TEST2
TEST2
TEST2

nc -w

制限事項

nc(netcat)によるタイムアウトは秒単位での指定。ミリ秒単位ではできない。

関連

1
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
1
2