Baobab
Baobab

Reputation: 157

accessing tcp using python

looking for help with the following. I need to access live weather data made available on port 5556 of my device using python so I can then process it further.

The command nc 127.0.0.1 5556 at the command promt results in the following response:

20201107175011 th0 -0.5 93 -1.5 0
20201107175055 wind0 0 0.0 0.0 -0.5 0
20201107175045 rain0 0.0 153.8 0.0 0
20201107175041 thb0 21.6 32 4.2 899.0 1006.0 0 1
20201107175028 data10 0.00 0
20201107175028 data11 61.84 0
20201107175028 data12 1.00 0
20201107175028 data13 12.00 0
20201107175028 data15 106.00 0
20201107175028 data16 1.00 0
20201107175028 t9 50.5 0

Utilizing the following python script results in: OSError: [Errno 98] Address in use.

    !/usr/bin/env python

    import socket
    
    HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
    PORT = 5556        # Port to listen on (non-privileged ports are > 1023)
    
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        s.listen()
        conn, addr = s.accept()
        with conn:
            print('Connected by', addr)
            while True:
                data = conn.recv(1024)
                if not data:
                    break
                print(data)

What am I doing wrong? Is there a way for python to receive the same response that is received using netcat?

Thanks.

Baobab

Upvotes: 0

Views: 678

Answers (1)

Baobab
Baobab

Reputation: 157

Using a client script rather than a server script works. Thanks.

#!/usr/bin/env python3

import socket

HOST = '127.0.0.1' 
PORT = 5556       

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    data = s.recv(1024)

print('Received', repr(data))

Upvotes: 1

Related Questions