Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 412
Ravi Krishnamoorthy Avatar asked May 01 '16 11:05

Ravi Krishnamoorthy


1 Answers

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.)

like image 190
fuenfundachtzig Avatar answered Sep 22 '22 00:09

fuenfundachtzig