Ravi Krishnamoorthy
Ravi Krishnamoorthy

Reputation: 67

why do i get a bad file descriptor error?

i got an error for bad file descriptor for this code for the udp server program i made

from socket import *

s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', 890))

while True:
   (c,a) = s.recvfrom(1024)
   msg = 'thanks for requesting'
   s.sendto(msg,a)
   s.close()

the error message i got was

Traceback (most recent call last):
File "udpserv.py", line 7, in <module>
(c,a) = s.recvfrom(1024)
 File "/usr/lib/python2.7/socket.py", line 174, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor

can anyone please tell me how i got this error and how to solve it?

Upvotes: 6

Views: 14978

Answers (2)

Sabin Chacko
Sabin Chacko

Reputation: 761

You can get that same error if you have an infinite while loop. In my case I replaced the

while True:

with

count = 0
while (count < 10):
    count += 1
    #rest of the code

Upvotes: 1

fuenfundachtzig
fuenfundachtzig

Reputation: 8352

You get this error because you close the socket and then call recvfrom again.

If you add a print after the line with recvfrom, you'll notice that the first call to recvfrom works as expected. The second call (after looping once) throws the error you see.

Fix your code by simply removing s.close(). (You don't need to close the connection to the client as UDP doesn't have that concept, in contrast to TCP if you had that in mind.)

Upvotes: 9

Related Questions