Listening to port and capturing data in python

Listening to port and capturing data in python

This sounds like homework… You havent tried to do it.

In python, to receive and send data (and definitely exchange data), we use the library called socket. You have two have to scripts, a server-side (which youve written in C) and a client-side script.

# client example

import socket, time
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((localhost, 5000))
while True:
    time.sleep(5)
    data = client_socket.recv(512)
    if data.lower() == q:
        client_socket.close()
        break

    print(RECEIVED: %s % data)
    data = input(SEND( TYPE q or Q to Quit):)
    client_socket.send(data)
    if data.lower() == q:
        client_socket.close()
        break

This is a client-side script example, which receives the data each 5 secs and prints it out. I hope you can adapt it to fit your needs.

Source: Basic Python client socket example

Install tcpflow

Run the given script

import os

INTERFACE = lo

PORT = 30003

os.system(tcpflow -i %s port %s % (INTERFACE, PORT))

It will write the requests which are coming to the port into a file like 127.000.000.001.06080-127.000.000.001.6347 in scripts location

Listening to port and capturing data in python

Leave a Reply

Your email address will not be published. Required fields are marked *