mongodbpymongoping

pymongo pinging and ping from terminal


I have a very simple test script

from pymongo import MongoClient
from pymongo.errors import ConnectionFailure

try:
    client = MongoClient('mongodb://your_host:your_port')
    client.admin.command('ping')  # Sends a ping command to the server
    print("Connection successful!")
except ConnectionFailure:
    print("Failed to connect to MongoDB server.")

When I run it, it shows that the connection from my pc to the host is successful. However turns out that I can not ping the host from my terminal (it seems it is due to the particular setting of the VPN I am using)(I am not seeking to particularly resolve this issue)

ping your_host -c 1
 ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms

So my question is, client.admin.command('ping') is not throwing an exception, so what does this command actually involve? I suspect it is just transmit but not receive packets. so is that the difference with the command ping from terminal?

Is there an alternative way to check if the connection to host is successful (without ping)?

EDIT: I have been asked

Why do you try to ping the database when you have successfully connected to it? When the connection was done successfully then it is working - why do you want to check twice?

My apologies for not explaining. In reality the script above was just a test script and not the main one in which I am working. In the main script, the script first sends a ping but with a ping from the terminal. It obviously fails (since as I explained, my machine cannot ping the host).

However I found out that when pinging using pymongo, I can ping successfully. (not that I need to ping) so I want to understand why I can ping there but not from terminal.

( I have been told that the configuration of my VPN does not permit pinging, which explains the failure of the terminal command but why does it work with pymongo?)


Solution

  • When you say "ping from the terminal" I assume you mean the ping network utility provided by the operating system.

    The network utility uses ICMP, not TCP, sending an ICMP echo request without requiring a connection to be established. The expected response is an ICMP echo reply. This is trivially blocked by firewalls while permitting any TCP traffic.

    The MongoDB ping database command requires that a connection to the database has already been established. Pymongo sends an OP_MSG containing the command name "ping" over the established TCP connection. The database server then responds with its own OP_MSG containing "ok: 1".

    Despite having the same name, these two operations serve slightly different purposes using very different methods.