在Angus的帮助下,本小菜实现了人生第一个VC++6.0网络程序ping
实现的功能是:2台电脑联通后有“Reply from192.168.0.***:Byte:32 time:0ms TTL:128”
美中不足的是:拔掉网线后再ping该IP地址,程序处于长时间检测状态,而无显示timeout错误提示。
请大家帮助。
[此贴子已经被作者于2006-6-7 9:56:18编辑过]
这个是pingDlg.cpp
// pingDlg.cpp : implementation file
//
#include "stdafx.h"
#include "ping.h"
#include "pingDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define ICMP_ECHO 8 //ICMP请求响应
#define ICMP_REPLY 0 //ICMP响应
#define BUFSIZE 1024 //缓冲区的大小
#define TIMES 20 //默认的PING次数
#define TIMEOUT 1000 //最长的等待时间
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
//求ICMP的头校验和
WORD CheckSum(WORD *buffer,int size)
{
WORD cksum=0;
while(size>1)
{
cksum+=*buffer++;
size-=sizeof(WORD);
}
if(size)
cksum+=*(UCHAR*)buffer;
cksum=(cksum>>16)+(cksum&0xffff);
cksum+=(cksum>>16);
return(~cksum);
}
//ping一次
BOOL PingOnce(SOCKET hsock,CPingDlg* pDlg)
{
char sendByte[BUFSIZE];
char recvByte[BUFSIZE];
int sendBytesCount;
int recvBytesCount;
int sendsize;
int recvsize;
int IPHeaderSize;
DWORD* ptime;
DWORD sendTime,recvTime;
struct IPHeader* pIP;
struct ICMPHeader* pICMP;
SOCKADDR_IN s_sockaddr;
SOCKADDR_IN d_sockaddr;
CString Info;
//设置目的计算机的socket
d_sockaddr.sin_family =AF_INET;
d_sockaddr.sin_addr =*(LPIN_ADDR)*(pDlg->m_lpHostEnt ->h_addr_list );
//设置待传递的ICMP头
pICMP=(struct ICMPHeader*)sendByte;
pICMP->type=ICMP_ECHO;// 请求响应标志
pICMP->code=0;
pICMP->ID=(WORD)GetCurrentProcessId();
pICMP->seq=0;
pICMP->checksum=0;
ptime=(DWORD*)(sendByte+sizeof(struct ICMPHeader));
sendTime=GetTickCount();//取发送的时刻
*ptime=sendTime;
sendsize=sizeof(struct ICMPHeader)+sizeof(DWORD);
//求ICMP头的校验和
pICMP->checksum =CheckSum((WORD*)pICMP,sendsize);
//用socket发送数据报
sendBytesCount=sendto(hsock,(LPSTR)pICMP,sendsize,0,(LPSOCKADDR)&d_sockaddr,sizeof(d_sockaddr));
//判断传送是否成功
if(sendBytesCount==SOCKET_ERROR)
{
if(WSAGetLastError()==WSAETIMEDOUT)
pDlg->m_ListInfo.InsertString(pDlg->m_ListInfo.GetCount(),"Request time out...");
return FALSE;
}
if(sendBytesCount<sendsize)
return FALSE;
recvsize=sizeof(s_sockaddr);
//接收响应数据报
recvBytesCount=recvfrom(hsock,recvByte,BUFSIZE,0,(LPSOCKADDR)&s_sockaddr,&recvsize);
//取接收到数据报的时刻
recvTime=GetTickCount();
//判断接收过程是否出错
if(recvBytesCount==SOCKET_ERROR)
{
if(WSAGetLastError()==WSAETIMEDOUT)
pDlg->m_ListInfo.InsertString(pDlg->m_ListInfo.GetCount (),"Request time out...");
return FALSE;
}
pIP=(struct IPHeader*)recvByte;
//取IP头的长度
IPHeaderSize=(BYTE)(pIP->verlen <<4)>>2;
if(recvBytesCount<IPHeaderSize+(int)sizeof(struct ICMPHeader))
return FALSE;
pICMP=(struct ICMPHeader*)(recvByte+IPHeaderSize);
//判断是否响应的数据报
if(pICMP->type!=ICMP_REPLY)
return FALSE;
//判断是否是上一个传送函数发送的数据报的响应
if(pICMP->ID!=(WORD)GetCurrentProcessId())
return FALSE;
//如果数据接收成功,则显示数据
Info.Format(":Bytes:%d time:%dms TTL:%d",recvBytesCount, recvTime-sendTime,(UINT)pIP->TTL);
Info=inet_ntoa(*(LPIN_ADDR)*(pDlg->m_lpHostEnt->h_addr_list))+Info;
Info="Reply from"+Info;
pDlg->m_ListInfo.InsertString(pDlg->m_ListInfo.GetCount(),Info);
return TRUE;
}
//为ping开的线程的主函数
DWORD WINAPI DoPing(LPVOID lpparameter)
{
LPINFO temp=(LPINFO)lpparameter;
UINT times=0;//控制ping的次数
while((temp->flag)&&(times<temp->times))
{
PingOnce(temp->hsock,(CPingDlg*)temp->pdlg);
times++;
}
return 0;
}//自主添加完毕
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CPingDlg dialog
CPingDlg::CPingDlg(CWnd* pParent /*=NULL*/)
: CDialog(CPingDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CPingDlg)
m_IPAddr = _T("");
m_Times = 20;
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CPingDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CPingDlg)
DDX_Control(pDX, IDC_LIST_INFO, m_ListInfo);
DDX_Text(pDX, IDC_EDIT_IP, m_IPAddr);
DDX_Text(pDX, IDC_EDIT_TIMES, m_Times);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CPingDlg, CDialog)
//{{AFX_MSG_MAP(CPingDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON_PING, OnButtonPing)
ON_BN_CLICKED(IDC_BUTTON_STOP, OnButtonStop)
ON_WM_DESTROY()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CPingDlg message handlers
BOOL CPingDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
SetDlgItemText(IDC_EDIT_IP, "192.168.164.201");
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
}
void CPingDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CPingDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CPingDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
//响应按钮ping的消息
void CPingDlg::OnButtonPing()
{
// TODO: Add your control notification handler code here
//自主添加
CString strIP;
LPPROTOENT lpproto;
int proto;
SOCKET hsock;
int returncode;
int timeout;
CString Errmsg;
DWORD ThreadID;
DWORD code;
//删除m_ListInfo中的所有信息
while(m_ListInfo.GetCount()!=0)
m_ListInfo.DeleteString(m_ListInfo.GetTopIndex());
//取得m_lpHostEnt
if(!GetHostEnt())
{
Errmsg.Format("There is no this host computer.");
m_ListInfo.InsertString(m_ListInfo.GetCount(),"Connecting...");
}
//取得协议的类型
lpproto=getprotobyname("icmp");
if(lpproto==NULL)
proto=IPPROTO_ICMP;
else
proto=lpproto->p_proto;
//生成Socket句柄
hsock=WSASocket(AF_INET,SOCK_RAW,proto,NULL,0,0);
if(hsock==INVALID_SOCKET)
{
Errmsg.Format("Socker error");
m_ListInfo.InsertString(m_ListInfo.GetCount(),(LPCTSTR)Errmsg);
return;
}
timeout=TIMEOUT;
//设置最长的接收时间
returncode=setsockopt(hsock,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,sizeof(timeout));
if(returncode==SOCKET_ERROR)
{
Errmsg.Format("Socker error");
m_ListInfo.InsertString(m_ListInfo.GetCount(),(LPCTSTR)Errmsg);
return;
}
timeout=TIMEOUT;
//设置最长的发送时间
returncode=setsockopt(hsock,SOL_SOCKET,SO_SNDTIMEO,(char*)&timeout,sizeof(timeout));
if(returncode==SOCKET_ERROR)
{
Errmsg.Format("Socket srror");
m_ListInfo.InsertString(m_ListInfo.GetCount(),(LPCTSTR)Errmsg);
return;
}
m_Info.flag=TRUE;
m_Info.hsock=hsock;
m_Info.pdlg=this;
//取得用户设定的ping次数
UpdateData(TRUE);
if(m_Times<=0)
m_Info.times=m_Times=TIMES;
else
m_Info.times=m_Times;
UpdateData(FALSE);//对数据进行回显
//创建ping的线程
if(!GetExitCodeThread(m_hThread,&code)||(code!=STILL_ACTIVE))
m_hThread=CreateThread(NULL,0,DoPing,&m_Info,0,&ThreadID);
if(m_hThread==NULL)
MessageBox("Create thread ping failed!");
}
BOOL CPingDlg::GetHostEnt()
{
UpdateData(TRUE);
//如果用户输入的数据是主机名
m_lpHostEnt=gethostbyname((LPCSTR)m_IPAddr);
if(m_lpHostEnt==NULL)
{
DWORD dwIP;
dwIP=inet_addr((LPCSTR)m_IPAddr);
//如果用户输入的是IP地址
m_lpHostEnt=gethostbyaddr((LPSTR)&dwIP,4,AF_INET);
if(m_lpHostEnt==NULL)
return FALSE;
}
return TRUE;
}
void CPingDlg::OnButtonStop()
{
// TODO: Add your control notification handler code here
DWORD code;
//设置停止标志
m_Info.flag=FALSE;
Sleep(TIMEOUT);
//如果线程还没有停止,则强制它停止
if(GetExitCodeThread(m_hThread,&code))
if(code==STILL_ACTIVE)
{
TerminateThread(m_hThread,0);
CloseHandle(m_hThread);
}
}
void CPingDlg::OnOK()
{
OnButtonStop();
CDialog::OnOK();
// TODO: Add extra validation here
}
void CPingDlg::OnDestroy()
{
OnButtonStop();
CDialog::OnDestroy();
// TODO: Add your message handler code here
}