Skip to content
Advertisement

Why does my TCP connection not provide a response to a message when it works OK in netcat (nc) and telnet?

I am trying to send a message to a socket and read the response back in either PHP or Python. I have tried Telneting into the IP/Port and manually sending a command/receiving a response to verify the server is operating as expected. I have also tried connecting using nc (netcat) and that also works fine. In both cases I get a response immediately after sending a test string.

When I try to code it, I am seemingly able to successfully open a socket and send a message, but there is never a response after sending the test message. I’ve tried coding it in PHP & Python and the result is the same – nothing seems to be waiting to be read back from the socket. The read just times out with a blank response.

This is an example of what I do with nc to test the connection:

$ nc 192.168.85.251 10001
tC <--- I type this, and press enter. 
tRIN. <--- this is the response

Here’s the Python code I’ve been using:

#!/usr/bin/env python3

import socket

HOST = '192.168.85.251'  # The server's hostname or IP address
PORT = 10001        # The port used by the server

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

print('Received', repr(data))

Here’s the equivalent PHP:

<?php

  $host="192.168.85.251";
  $port = 10001;
  $payload = "tC" . Chr(10);
  $fp = fsockopen ($host, $port, $errno, $errstr);

 if (!$fp){
        $result = "Error: could not open socket connection";
}

else {
        // write the user string to the socket
        fputs ($fp, $payload);
        socket_set_timeout($fp, 5);
        $feedback = fgets ($fp, 2);
        echo "Returned: ". $feedback  . " ENDn";
 }
?>

Can anyone suggest where I might be going wrong?

Advertisement

Answer

s.sendall(b’tCr’)

This is not what is done with telnet or nc. With these tools either b'tCn' or b'tCrn' is send but not b'tCr'. Likely the server does not respond since the expected message is not (fully) received.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement