本文发表在 rolia.net 枫下论坛void CIpSearchDlg::OnSearchBtn()
{
// to do a search, a ip address file must have been opened,
// and the ip address to be searched must have been keyed in
UpdateData(TRUE);
BYTE inField1, inField2, inField3, inField4, inMaskBits;
DWORD inIp, inMask;
BYTE field1, field2, field3, field4, maskBits;
DWORD Ip, Mask;
DWORD MaskWhenCompare;
int nRet;
if ( m_ip.IsEmpty() == TRUE )
{
MessageBox("Specify the IP address to be searched.",
NULL, MB_ICONEXCLAMATION | MB_OK );
return;
}
else
{
nRet = sscanf(m_ip, "%d.%d.%d.%d/%d",
&inField1, &inField2, &inField3, &inField4, &inMaskBits);
if ( nRet < 4 )
{
MessageBox("The specified IP address is not valid.",
NULL, MB_ICONEXCLAMATION | MB_OK);
return;
}
if ( nRet == 5 )
{
if ( inMaskBits > 32 )
{
MessageBox("The specified IP address mask is not valid.",
NULL, MB_ICONEXCLAMATION | MB_OK);
return;
}
// netmask is specified
inMask = MakeNetMask(inMaskBits);
}
else
inMask = 0;
inIp = MakeDWord(inField1, inField2, inField3, inField4);
}
if ( m_ipFile.m_hFile == CFile::hFileNull )
{
MessageBox("Specify the IP address file to search in.",
NULL, MB_ICONEXCLAMATION | MB_OK );
return;
}
// do the string search
BeginWaitCursor();
m_ipFile.SeekToBegin();
CString lineBuffer;
BOOL found = FALSE;
while ( m_ipFile.ReadString(lineBuffer) )
{
if ( lineBuffer.GetLength() < 1 )
continue;
nRet = sscanf(lineBuffer, "%d.%d.%d.%d/%d",
&field1, &field2, &field3, &field4, &maskBits);
if ( nRet < 4 )
continue;
if ( nRet == 5 )
{
if ( maskBits > 32 )
continue;
Mask = MakeNetMask(maskBits);
}
else
Mask = 0;
Ip = MakeDWord(field1, field2, field3, field4);
if ( inMask || Mask )
{
if ( inMask && Mask )
MaskWhenCompare = inMask > Mask? Mask : inMask;
else if ( inMask )
MaskWhenCompare = inMask;
else
MaskWhenCompare = Mask;
}
else
MaskWhenCompare = MakeNetMask(32); // this can be made as a constant global
// for a better speed performance
if ( (Ip & MaskWhenCompare) == (inIp & MaskWhenCompare) )
{
CString displayMsg;
displayMsg = m_ip + " ==> Found: " + lineBuffer;
m_resultList.AddString(displayMsg);
found = TRUE;
break;
}
}
if ( !found )
{
lineBuffer.Format("%s ==> Not Found", m_ip);
m_resultList.AddString(lineBuffer);
}
m_resultList.SetCurSel(m_resultList.GetCount() - 1);
EndWaitCursor();
}更多精彩文章及讨论,请光临枫下论坛 rolia.net