Search code examples
macosqtcocoafile-sharingfileshare

How to query if a particular folder is shared or enumerate folders shared from the local machine on osx in C/C++ or Objective C


I'm currently developing on macOS High Sierra (not Windows) using Qt. Just using regular macOS rather than macOS server. I'm happy to write Mac-only code outside the Qt bubble to fix this problem, obviously.

I'm looking for a way to programmatically check in C/C++ or Objective-C whether a particular local folder is shared on the local network. Alternatively I'd like to retrieve a list of all shared folders. I'd like the method to work on a reasonably large range of macOS versions e.g. 10.9 to 10.14.

I need to do this in order to rewrite paths to local files as UNC paths so that they are accessible from a Windows client machine on the same network via SMB sharing with suitable credentials. This does assume shared folders have already been setup but if they haven't the user will receive an error and be prompted to share suitable folders.

I can share/un-share and see the sharing status of a folder using the Get Info dialog in Finder but I'm looking for something I can use within an application.

Things I've tried without success:

  • Searching for other instances of the problem
  • NSURL class - doesn't document a resource name to query for its sharing status.
  • smbutil doesn't seem to list shares being shared from the machine it's running on.
  • smbd doesn't seem to have any command line options to query shared folders.
  • The various configuration files mentioned in the smbutil and smbd.conf man pages don't contain a list of shared folders
  • mdls doesn't contain any relevant metadata in the output for folders that are shared.
  • ls -l@ doesn't list any extra information for shared folders
  • Sharing an unusually named folder and greping the hard disk for the folder name including binary files to see if this information is persisted somewhere. Presumably it is persisted somehow because the folder is shared after rebooting but I can't find any record of the folder name anywhere.
  • OpenDirectory services seem to contain lots of references to SMB in the headers but I can't see a way to use OpenDirectory to get a list of folders shared from the local machine.
  • Sharing the root folder so that the rewriting is trivial. This works but it's pretty undesirable to share a root folder.
  • Perhaps there's a better way of doing the access that will sidestep the need for having and querying SMB shares...?

Solution

  • Found the answer elsewhere on stackexchange answered by mivk.

    Run the following command and capture the output.

    sharing -l

    This gives a slightly verbose list of file shares with separate details for afp and smb which can be parsed to get a list of shared folders on the local machine. Tested on Catalina. It's possible that this command will fail to run if file sharing is not enabled in System Preferences.