我有一个名为ReversedIPAddressString的函数,它将IPAddress作为TCHAR *,然后将尊重的IPAddress作为TCHAR *返回。我能够反转IP,但是当我将这个TCHAR *指针(reversIP)传递给其他函数(比如dns.query(TCHAR *))时,IP值总是垃圾。我想知道我错过了什么?
我在这里粘贴我的代码供您参考......
bool DNSService::DoesPtrRecordExixts(System::String^ ipAddress)
{
IntPtr ipAddressPtr = Marshal::StringToHGlobalAuto(ipAddress);
TCHAR* ipAddressString = (TCHAR*)ipAddressPtr.ToPointer();
bool bRecordExists = 0;
WSAInitializer initializer;
Locale locale;
// Initialize the identity object with the provided credentials
SecurityAuthIdentity identity(userString,passwordString,domainString);
// Initialize the context
DnsContext context;
// Setup the identity object
context.acquire(identity);
DnsRecordQueryT<DNS_PTR_DATA> dns(DNS_TYPE_PTR, serverString);
try
{
bRecordExists = dns.query(ReversedIPAddressString(ipAddressString)) > 0;
}
catch(SOL::Exception& ex)
{
// Free up the pointers to the resources given to this method
Marshal::FreeHGlobal(ipAddressPtr);
if(ex.getErrorCode() == DNS_ERROR_RCODE_NAME_ERROR)
return bRecordExists;
else
throw SOL::Exception(ex.getErrorMessage());
}
// Free up the pointers to the resources given to this method
Marshal::FreeHGlobal(ipAddressPtr);
return bRecordExists;
}
TCHAR* DNSService::ReversedIPAddressString(TCHAR* ipAddressString)
{
TCHAR* sep = _T(".");
TCHAR ipArray[4][4];
TCHAR reversedIP[30];
int i = 0;
TCHAR* token = strtok(ipAddressString, sep);
while(token != NULL)
{
_stprintf(ipArray[i], _T("%s"), token);
token = strtok((TCHAR*)NULL, sep);
i++;
}
_stprintf(reversedIP, _T("%s.%s.%s.%s.%s"), ipArray[3], ipArray[2], ipArray[1], ipArray[0],_T("IN-ADDR.ARPA"));
return reversedIP;
}
int query(__in const TCHAR* hostDomain, __in DWORD options=DNS_QUERY_STANDARD)
希望得到你的帮助。
提前致谢!
拉马尼
答案 0 :(得分:0)
您将返回一个指向本地数组TCHAR reversedIP[30];
的指针,该数组已使用您的函数ReversedIPAddressString
进行分配。当此函数退出时,您的数组将超出范围 - 它不再存在。这是未定义的行为。
您应该返回一个字符串对象,例如std::basic_string<TCHAR>
请参阅此问题:pointer-to-local-variable