1

Is there any simple way to tell if UNC path points to a local machine. I found the following question SO

Is there any WIN32 API that will do the same?

Community
  • 1
  • 1
SparcU
  • 742
  • 1
  • 7
  • 27
  • The [PathIsSameRoot](http://msdn.microsoft.com/en-us/library/windows/desktop/bb773687%28v=vs.85%29.aspx) function sounds promising. I don't know if it accepts UNC paths, though. – Andrew Lambert Apr 05 '12 at 18:30

1 Answers1

0
#include <windows.h>
#include <WinSock.h>
#include <string>
#include <algorithm>

#pragma comment(lib, "wsock32.lib")

using namespace std;

std::wstring ExtractHostName( const std::wstring &share )
{
if (share.size() < 3 )
    return L"";
size_t pos = share.find(  L"\\", 2 );
wstring server = ( pos != string::npos ) ? share.substr( 2, pos - 2 ) : share.substr( 2 );
transform( server.begin(),server.end(), server.begin(), tolower); 
return server;
}

bool IsIP( const std::wstring &server )
{
size_t invalid = server.find_first_not_of(  L"0123456789." );
bool fIsIP = ( invalid == string::npos );
return fIsIP;
}

bool IsLocalIP( const std::wstring &ipToCheck )
{

if ( ipToCheck == L"127.0.0.1" )
    return true;    

WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD( 1, 1 );
if ( WSAStartup( wVersionRequested, &wsaData ) != 0 )
    return false;

bool fIsLocal = false;

char hostName[255];
if( gethostname ( hostName, sizeof(hostName)) == 0 )
{
    PHOSTENT hostinfo;      
    if(( hostinfo = gethostbyname(hostName)) != NULL )
    {
        for (int i = 0; hostinfo->h_addr_list[i]; i++)
        {
            char *ip = inet_ntoa(*( struct in_addr *)hostinfo->h_addr_list[i]);
            wchar_t wcIP[100]={0};
            ::MultiByteToWideChar(CP_ACP, 0, ip, -1, wcIP, _countof(wcIP));
            if (ipToCheck == wcIP) 
            {
                fIsLocal = true;
                break;
            }
        }
    }
}
WSACleanup();
return fIsLocal;
}

bool IsLocalHost( const std::wstring &server )
{
if (server == L"localhost")
    return true;    

bool fIsLocalHost = false;

wchar_t buffer[MAX_PATH]={0};
DWORD dwSize =  _countof(buffer);
BOOL fRet = GetComputerName( buffer, &dwSize );
transform( buffer, buffer + dwSize, buffer, tolower); 
fIsLocalHost = ( server == buffer );
return fIsLocalHost;
}

bool ShareIsLocal( const std::wstring &share )
{
wstring server = ExtractHostName( share );
bool fIsIp = IsIP( server );
if ( fIsIp )
    return IsLocalIP( server );
else
    return IsLocalHost( server );
} 
SparcU
  • 742
  • 1
  • 7
  • 27