Checking connection in the loop to prevent HostNotFoundException