Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mount a network drive in linux using c++

Tags:

c++

c

linux

mount

I want to mount a network drive on linux using c++. Using the command line of "mount" , I am able to mount any drive I want. But using C++, Only those drives are mounted successfully which are shared by the user.

This 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 "C:/Users" drive of the machine. Using the Command line, It works but not by this code. I don't know why. The error printed by strerror() is "No such device or address". I am using Centos and Samba is configured for this machine. Where am I going wrong?

like image 349
user2914066 Avatar asked Jun 19 '26 03:06

user2914066


1 Answers

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

$ 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 for 127.0.1.1 in the ip option), and passing in the full UNC with backslashes to the mount system call.

Rewriting your example with my mount options we have:

#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 when writing your tool to invoke mount2.

like image 130
Petesh Avatar answered Jun 21 '26 16:06

Petesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!