如果你編寫Internet應用程序, 你需要校驗用戶進入的IP地址和確認它是正確的.
首先,我們需要在對話框的頭文件裡加入下面的函數聲明:
#include <winsock.h>
void WINAPI DDX_IPAddress(CDataExchange* pDX, int nIDC, UINT & value);
實現數據交換,你需要在你的對話框DoDataExchange函數裡調用DDX_IPAddress函數。
現在,在對話框的實現文件中加入下列代碼,不要忘記在項目設置中包含ws2_32.lib.
// DDX routine fo IP address translation
void WINAPI DDX_IPAddress(CDataExchange* pDX, int nIDC, UINT & value)
{
// from dialog to class ?
if( pDX->m_bSaveAndValidate)
{
CString Val;
BOOL bValid = true;
pDX->m_pDlgWnd->GetDlgItem(nIDC)->GetWindowText(Val);
for( int i = 0; i < Val.GetLength(); i++)
{
// lets check if all entered char in entered
// IP address are digits
if(Val[i] == .)
continue;
if(isdigit(Val[i]) == 0)
{
bValid = false;
break;
}
}
if(bValid)
{
value = inet_addr(Val);
if(value == INADDR_NONE)
{
pDX->m_pDlgWnd->MessageBox("The entered IP address is invalid.");