#################################################################################################################################################################
# udp_echo.py v 0.1/20180915 - UDP LISTENER [ECHO] EXAMPLE
# COPYRIGHT (c) 2018 Dragos Iosub / R&D Software Solutions srl
#
# You are legaly entitled to use this SOFTWARE ONLY IN CONJUNCTION WITH xyz-mIOT by itbrainpower.net or u-GSM by itbrainpower.net DEVICES USAGE. Modifications, 
# derivates and redistribution of this software must include unmodified this COPYRIGHT NOTICE. You can redistribute this SOFTWARE and/or modify it under the 
# terms of this COPYRIGHT NOTICE. Any other usage may be permited only after written notice of Dragos Iosub / R&D Software Solutions srl.
# 
# This SOFTWARE is distributed is provide "AS IS" in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# 
# Dragos Iosub, Bucharest 2018.
# https://itbrainpower.net
#################################################################################################################################################################
# tested with python 2.6
# if your server is behind firewall, ECHO reply may fail to reach the NB IoT modem
# you may launch this utility:
# "sudo python udp_echo.py"
# or,
# "sudo python udp_echo.py > echo.txt 2>&1 &"
# in this case, "tail -f echo.log" may help you
#################################################################################################################################################################
import socket
import sys

listener_address = '259.259.259.259'   #replace with your server IP
listener_port = 17667

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = (listener_address,listener_port)
print >>sys.stderr, 'listen on %s port %s' % server_address

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(server_address)
while True:
    print >>sys.stderr, '\nwait to receive message'
    data, address = sock.recvfrom(512)
    print >>sys.stderr, '\nreceived %s bytes from %s' % (len(data), address)
    print >>sys.stderr, data
    clientaddress = address[0]
    clientport = address[1]

    if data:
        sent = sock.sendto(data, address)
        print >>sys.stderr, 'sent %s bytes back to %s' % (sent, clientaddress)
