C++ – Use C++ to mount a network drive in Linux

Use C++ to mount a network drive in Linux… here is a solution to the problem.

Use C++ to mount a network drive in Linux

I want to mount a network drive on Linux using C++. Using the “mount” command line, I can mount any drive I want. But with C++, only those drives that are shared by the user can install successfully.

Here is my test code :

#include <sys/mount.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <string>

using namespace std;

int main()
{
  string src = "//192.168.4.11/c$/Users";
  string dst = "/home/krahul/Desktop/test_mount";
  string fstype = "cifs";

printf("src: %s\n", src.c_str());

if( -1 == mount(src.c_str(), dst.c_str(), fstype.c_str(), MS_MGC_VAL | MS_SILENT , "username=uname,password=pswd") )
  {
      printf("mount failed with error: %s\n",strerror(errno));
  }
  else
      printf("mount success!\n");

if( umount2(dst.c_str(), MNT_FORCE) < 0 )
  {
      printf("unmount failed with error: %s\n",strerror(errno));
  }
  else
      printf("unmount success!\n");

return 0;
}

I want to mount the machine’s “C:/Users” drive. Using the command line, it works, but not through this code. I don’t know why. The error printed by strerror() is “There is no such device or address”. I am using Centos and I have Samba configured for this machine. Where am I wrong?

Solution

The mount.cifs command parses and changes the options passed to the mount system call. Use the -v option to see what it uses for system calls.

$ mount -v -t cifs -o username=guest,password= //bubble/Music /tmp/xxx
mount.cifs kernel mount options: ip=127.0.1.1,unc=\\bubble\Music,user=guest,pass=********

i.e. it gets the IP address of the target system (replacing my bubble with 127.0.1.1 in the ip option) and passes the full UNC with a backslash to the mount system call

Rewrite your example with my mount options:

#include <sys/mount.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <string>

using namespace std;

int main()
{
  string host = "127.0.1.1";
  string src = "\\\\bubble\\Music";
  string dst = "/tmp/xxx";
  string fstype = "cifs";

string all_string = "unc=" + src + ",ip=" + host + ",username=guest,password=";

printf("src: %s\n", src.c_str());

if( -1 == mount(src.c_str(), dst.c_str(), fstype.c_str(), MS_MGC_VAL | MS_SILENT , all_string.c_str()))
  {
      printf("mount failed with error: %s\n",strerror(errno));
  }
  else
      printf("mount success!\n");

if( umount2(dst.c_str(), MNT_FORCE) < 0 )
  {
      printf("unmount failed with error: %s\n",strerror(errno));
  }
  else
      printf("unmount success!\n");

return 0;
}

This should help you write a tool to call mount2.

Related Problems and Solutions