Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Errno 9: Bad file descriptor in python socket

Tags:

python

sockets

My code is this:

while 1:
    # Determine whether the server is up or down
    try:
        s.connect((mcip, port))
        s.send(magic)
        data = s.recv(1024)
        s.close()
        print data
    except Exception, e:
        print e
    sleep(60)

It works fine on the first run, but gives me Errno 9 every time after. What am I doing wrong?

BTW,

mcip = "mau5ville.com"
port = 25565
magic = "\xFE"
like image 578
Mike Savi Avatar asked Apr 11 '13 20:04

Mike Savi


People also ask

What is Errno 9 Bad file Descriptor?

Reason for getting error “oserror: [errno 9] bad file descriptor” : The internal state of the file object indicates the file is still open since f. close() was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that's not open.

What causes bad file descriptor?

Bad file descriptor; for example, I/O on a descriptor that has been closed or reading from a descriptor open only for writing (or vice versa). There are no child processes. This error happens on operations that are supposed to manipulate child processes, when there aren't any processes to manipulate.

What does Errno 9 mean?

It shows an error like: OSError: [Errno 9] Bad file descriptor. It means that the file defined in the program is already closed automatically while running the code.

What does bad file descriptor mean?

In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons: The fd is already closed somewhere. The fd has a wrong value, which is inconsistent with the value obtained from socket() api.


2 Answers

You're calling connect on the same socket you closed. You can't do that.

As for the docs for close say:

All future operations on the socket object will fail.

Just move the s = socket.socket() (or whatever you have) into the loop. (Or, if you prefer, use create_connection instead of doing it in two steps, which makes this harder to get wrong, as well as meaning you don't have to guess at IPv4 vs. IPv6, etc.)

like image 194
abarnert Avatar answered Oct 03 '22 15:10

abarnert


I resolved this problem in the past,

you have to create the socket before connect():

    s = socket(AF_INET, SOCK_STREAM)

then continue with:

    s.connect((mcip, port))
    s.send(magic)
    data = s.recv(1024)
    s.close()
    print dat
like image 37
mgrfn Avatar answered Oct 03 '22 14:10

mgrfn