1

I'm trying to read data from a TCP/IP port using python. You can see from the TCPView screenshot below that the data is flowing from the application successfully, but I'm getting nothing from the code below, (I get the first print output and then just a blinking cursor).

TCPView screenshot

import socket

TCP_IP = "127.0.0.1"
TCP_PORT = 31003
BUFFER_SIZE = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((TCP_IP, TCP_PORT))
print("connected: ", s)
data = s.recv(BUFFER_SIZE)
s.close()
print("received data: ", data)

The line

print("connected: ", s)

outputs the following: enter image description here

this indicates that the data is outputting to the local port 60840, rather than the local port 61893 which is indicated by TCPView. Changing the script to listen to the local port named in TCPView has no effect.

1
  • Dear Terry: On SO it's considered polite to up-vote and/or accept answers like this one which appears to be correct.
    – Bill Bell
    Jan 7, 2017 at 15:59

1 Answer 1

2

You're using a datagram (UDP) socket, when you want a stream (TCP) one. Instead of this:

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

You should have this:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1
  • No problem. Happy to help.
    – user325117
    Jan 7, 2017 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.