udpclient.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # This example code is in the Public Domain (or CC0 licensed, at your option.)
  2. # Unless required by applicable law or agreed to in writing, this
  3. # software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  4. # CONDITIONS OF ANY KIND, either express or implied.
  5. # -*- coding: utf-8 -*-
  6. from builtins import input
  7. import socket
  8. import sys
  9. # ----------- Config ----------
  10. PORT = 3333
  11. IP_VERSION = 'IPv4'
  12. IPV4 = '192.168.0.167'
  13. IPV6 = 'FE80::32AE:A4FF:FE80:5288'
  14. # -------------------------------
  15. if IP_VERSION == 'IPv4':
  16. host = IPV4
  17. family_addr = socket.AF_INET
  18. elif IP_VERSION == 'IPv6':
  19. host = IPV6
  20. family_addr = socket.AF_INET6
  21. else:
  22. print('IP_VERSION must be IPv4 or IPv6')
  23. sys.exit(1)
  24. try:
  25. sock = socket.socket(family_addr, socket.SOCK_DGRAM)
  26. except socket.error:
  27. print('Failed to create socket')
  28. sys.exit()
  29. while True:
  30. msg = input('Enter message to send : ')
  31. try:
  32. sock.sendto(msg.encode(), (host, PORT))
  33. reply, addr = sock.recvfrom(128)
  34. if not reply:
  35. break
  36. print('Reply[' + addr[0] + ':' + str(addr[1]) + '] - ' + str(reply))
  37. except socket.error as msg:
  38. print('Error Code : ' + str(msg[0]) + ' Message: ' + msg[1])
  39. sys.exit()