Testing socket connection in Python

This question will expand on: Best way to open a socket in Python
When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail.

Edit: I tried this:

try:
    s.connect((address, '80'))
except:
    alert('failed' + address, 'down')

but the alert function is called even when that connection should have worked.


Asked by: Walter116 | Posted: 28-01-2022






Answer 1

It seems that you catch not the exception you wanna catch out there :)

if the s is a socket.socket() object, then the right way to call .connect would be:

import socket
s = socket.socket()
address = '127.0.0.1'
port = 80  # port number is a number, not string
try:
    s.connect((address, port)) 
    # originally, it was 
    # except Exception, e: 
    # but this syntax is not supported anymore. 
except Exception as e: 
    print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
    s.close()

Always try to see what kind of exception is what you're catching in a try-except loop.

You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except statement for each one of them - this way you'll be able to react differently for different kind of problems.

Answered by: Cherry246 | Posted: 01-03-2022



Answer 2

You can use the function connect_ex. It doesn't throw an exception. Instead of that, returns a C style integer value (referred to as errno in C):

s =  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
s.close()
if result:
    print "problem with socket!"
else:
    print "everything it's ok!"

Answered by: Sawyer851 | Posted: 01-03-2022



Answer 3

You should really post:

  1. The complete source code of your example
  2. The actual result of it, not a summary

Here is my code, which works:

import socket, sys

def alert(msg):
    print >>sys.stderr, msg
    sys.exit(1)

(family, socktype, proto, garbage, address) = \
         socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)

try:
    s.connect(address) 
except Exception, e:
    alert("Something's wrong with %s. Exception type is %s" % (address, e))

When the server listens, I get nothing (this is normal), when it doesn't, I get the expected message:

Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')

Answered by: Catherine223 | Posted: 01-03-2022



Answer 4

12 years later for anyone having similar problems.

try:
    s.connect((address, '80'))
except:
    alert('failed' + address, 'down')

doesn't work because the port '80' is a string. Your port needs to be int.

try:
    s.connect((address, 80))

This should work. Not sure why even the best answer didnt see this.

Answered by: Samantha573 | Posted: 01-03-2022



Similar questions

python - MitM socket connection for testing?

I'm trying to establish a mitm connection between me and a server which does some strange disconnecting and re-connecting sockets to begin comunnication succesfully. The case is I know how to accomplish it in vb using socket events, but can't get to it with Python. In vb, the code would be: Private Sub SckClient_ConnectionRequest(ByVal requestID As Long) sckserver.Con...


unit testing - mocking a socket connection in Python

I am trying to write unit tests for a class in python. The class opens a tcp socket on init. I am trying to mock this out so that I can assert that connecting is called with the correct values but obviously doesn't actually happen in unit tests. I have tired MagicMock, patch, etc but I have not found a solution. My class so far looks like this import socket class MyClass(object): ...


Python Testing without sql connection

I am using sql to pull in values from 'lookup' table. I will use cursor and fetchall and then loop through values and place them into dictionary. I do not see reason to keep querying database(open conn, query, close conn) for every lookup performed when a dictionary of subset of data should suffice. Is this 'standard' practice to use dictionary in-lieu of table ? Is there a way to test this with different ...


testing - Test an SFTP Connection in Python

I previously asked a question about mocks and testing and it helped me to get all but one aspect of testing sorted. How to test an SFTP connection. I have a method: def _transfer_file(self, my_file): try: with pysftp.Connection(‘host’, username=username, password=password) as sftp: sftp.put(my_file) sftp.close() return True except Exception as e: # log an error with...


Connection unit testing in Python

I am new to Python unit testing and I am not sure how i can create a unit test of this function that returns a connection? def connection(self): connection = mysql.connector.connect(host='localhost', database='test', user='user', password='password', auth_plugin='mysql_native_password') return connection


mysql - Python Psycopg error and connection handling (v MySQLdb)

Is there a way to make psycopg and postgres deal with errors without having to reestablish the connection, like MySQLdb? The commented version of the below works with MySQLdb, the comments make it work with Psycopg2: results = {'felicitas': 3, 'volumes': 8, 'acillevs': 1, 'mosaics': 13, 'perat\xe9': 1, 'representative': 6....} for item in sorted(results): try: cur.execute("""insert into results...


python - Mysql Connection, one or many?

I'm writing a script in python which basically queries WMI and updates the information in a mysql database. One of those "write something you need" to learn to program exercises. In case something breaks in the middle of the script, for example, the remote computer turns off, it's separated out into functions. Query Some WMI data Update that to the database Query Other WMI data Update that to t...


python - Connection refused on Windows XP network

This is only marginally a programming problem and more of a networking problem. I'm trying to get a Django web app to run in my home network and I can't get any machines on the network to get to the web page. I've run on ports 80 and 8000 with no luck. Error message is: "Firefox can't establish a connection to the server at 192.168.x.x." I've tried using sockets in python from the client: i...


tcp - db connection in python

I am writing a code in python in which I established a connection with database. I have queries in a loop. While queries being executed in the loop , If i unplug the network cable it should stop with an exception. But this not happens, When i again plug yhe network cabe after 2 minutes it starts again from where it ended. I am using linux and psycopg2. It is not showing exception


java - How do you create an anonymous Python telnet connection?

I am trying to telnet into a server using Python on Windows XP. I can connect successfully by typing 'telnet HOST PORT' which creates an anonymous connection. But Python's telnetlib.Telnet(HOST, PORT) returns 'Connection refused'. Telnetting in Java also fails. Spelunking shows that Python tries to create an anonymous socket connection. My admin says he doesn't allow anonymous connections. But neither Python nor Java...


python db connection

I am having a script which makes a db connection and pereform some select operation.accroding to the fetch data i am calling different functions which also perform db operations.How can i pass db connection to the functions which are being called as i donot want to make new connection


file - SSH Connection with Python 3.0

How can I make an SSH connection in Python 3.0? I want to save a file on a remote computer where I have password-less SSH set up.


python - Running programs w/ a GUI over a remote connection

I'm trying to start perfmon and another program that have GUI's through a python script that uses a PKA ssh connection. Is it possible to do this? If so could anyone point me in the right direction?


python - How to increase connection pool size for Twisted?

I'm using Twisted 8.1.0 as socket server engine. Reactor - epoll. Database server is MySQL 5.0.67. OS - Ubuntu Linux 8.10 32-bit in /etc/mysql/my.cnf : max_connections = 1000 in source code: adbapi.ConnectionPool("MySQLdb", ..., use_unicode=True, charset='utf8', cp_min=3, cp_max=700, cp_noisy=False) But i...


python - Making sure that psycopg2 database connection alive

I have a python application that opens a database connection that can hang online for an hours, but sometimes the database server reboots and while python still have the connection it won't work with OperationalError exception. So I'm looking for any reliable method to "ping" the database and know that connection is alive. I've checked a psycopg2 documentation but can't find anything like that. Sure I ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top