0

I have a while loop for retrying to connect to a device. problem is, every time it does retry it is using the same socket descriptor(closing and opening again), is this safe?

while(retry)
  create socket
  read(use socket created before)
  if read fails
     close socket and retry

i want a new socket fd to connect with the server and read again. Is reusing the same one safe in case read has failed?

Karlson
  • 2,958
  • 1
  • 21
  • 48
maheshg
  • 339
  • 2
  • 7
  • 17

2 Answers2

2

If you actually close the socket then I would suggest to create a new socket since the fd used for to describe the socket is now invalid so your reuse of the same file descriptor could cause errors.

Normally though it's better to close the old and create a new one.

Karlson
  • 2,958
  • 1
  • 21
  • 48
  • I am closing the socket and creating the new one, but since i closed say socket fd 'x', when i try to create a new one immediately after that, it gives me 'x' as new socket fd. – maheshg Mar 21 '12 at 14:28
  • @user1035818 This is absolutely fine. The old `fd` and all the stuff associated with it has been released back to the OS, so even if the number you get is the same the resources are new. – Karlson Mar 21 '12 at 14:34
  • @user1035818 Related Question: http://stackoverflow.com/questions/4160347/close-vs-shutdown-socket – Karlson Mar 21 '12 at 14:34
  • You can't reuse a (connection based) socket once you've called `shutdown` on it. – Hasturkun Mar 21 '12 at 14:35
  • @Hasturkun Retested and removed that suggestion. – Karlson Mar 21 '12 at 14:37
1

since you called bind or connect on the socket, you can't change the address. you must close the socket and create the new one.

ilnar
  • 61
  • 2