i am working on some proof of concept study research project and have python udp socket server that listen received data. Client send data NAME and FAMILY NAME on UDP to server. I would like to receive that data on UDP socket server side and on receive send this data to mysql database with two fields f_name and l_name.
import socket
UDP_IP = "192.168.1.10"
UDP_PORT = 9000
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
print "UDP SERVER STARTED!"
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "MSG Received:", data
this example is taken from web and with this server i get data on console. I would like to have it like below and of course code/concept can be changed. This might be solved with scapy sniffer but that would be dirty. Conceptually i would like to have ti something like: 1. socekt server received data 2. parse data received and send this data to mysql
I started with this in mind but doesnt work
import socket
import MySQLdb
UDP_IP = "192.168.1.10"
UDP_PORT = 9000
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
print "UDP SERVER STARTED!"
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
def parse(data):
db = MySQLdb.connect("localhost","db_user","db_pass","directory_db")
cursor = db.cursor()
# Params to insert into DB
f_nameObj = re.search(r'NAME: (.*?) .*', data, re.M|re.I)
if f_name:
f_name = f_nameObj.group(1)
l_nameObj = re.search(r'SURNAME: (.*?) .*', data, re.M|re.I)
if l_name:
l_name = l_nameObj.group(1)
# MySQL EXECUTION
cursor.execute("""
INSERT INTO dictionary (f_name, l_name) VALUES (%s, %s)""",(f_name,l_name))
#
db.commit()
With this kind of udp server i see no messages so seems function that parse data is not working with server. Any help or guidance would be appreciated
In your server when you receive data
you don't call parse
function.You just print the content of data
. Add the line with the comment and see the result.
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
parse(data) # Call the Function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.