Added sock.close() to finally blocks to ensure socket is closed