0

I am trying to test a series of ports, and also set a timeout in which if the value is hit and the connection has not been established it will move onto the next port. If the connection is established before the timeout value is hit, I'd like to print the value. The catch is, I'm trying to do it in one line as a python script...

This works, to just test the port:

python -c "import socket; print(socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect_ex('192.168.3.78', 6061))"

However, this does not provide any timeout value, so when in my script it will just hang if the connection cannot be established.

I was attempting to do something like:

python -c "import socket; print(socket.socket(socket.AF_INET, socket.SOCK_STREAM).create_connection(('192.168.3.78', 6061), timeout=2))"

But I cannot get it to accept the timeout value or print it out how long it took to establish the connection. I was looking through the socket doc's but couldn't seem to find what I could change.

1 Answer 1

0

socket.create_connection() creates the SOCK_STREAM (tcp) socket object for you, so you don't call socket.socket(...). Therefore

python -c "import socket; print(socket.create_connection(('192.168.3.78', 6061), timeout=2))"

should do what you want.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the comment, but that comes back with > <socket._socketobject object at 0x7fc83d2a2a60> I'm not sure how to interpret that, shouldn't it return a 0 or something more readable?
True, printing the result of socket.create_connection() doesn't produce very useful output, but that's what your code did so I simply copied it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.