Search code examples
cmongodbmongo-c-driver

How to construct a URI with username password for mongo C driver.


I am using mongo 3.0.8. I have an authenticated user admin with password admin. I am able to connect to the mongo shell as follows.

mongo admin -u amdin -p amdin

However, i tried to connect to using the following C code. This gives me an error

WARNING: client: Failed to connect to: ipv4 127.0.0.1:27017, error: 111, Connection refused

char URI[256];
snprintf(URI,256,"mongodb://admin:[email protected]:27017/?authSource=admin");
mongoc_client_t *client = mongoc_client_new(URI);

Solution

  • The error error: 111, Connection refused is a networking error. Your URI expecting to find the server listening on port 27017 of the same machine (127.0.0.1). Possible issues:

    • Server not running
    • Server not on that port
    • Server is bound to the "real ip address" of the machine.
    • There is local firewall (e.g. iptables) blocking access
    • Maybe an SELinux problem?

    If this is a Linux box, these commands might help diagnose:

    netstat -an -A inet | grep LISTEN
    /sbin/iptables -L