请教为什么“setsockopt(s,SOL_SOCKET,SO_RCVTIMEO, (char *)&nRecvTimeOut, ...)”不管用!!!

舟中夜起 2001-06-20 02:23:00
我现在自己来设定为非阻塞模式的方法,然后自己计算超时可以搞定,但是不明白用setsockopt为什么就不行,msdn明明说明支持的啊!!!

大师可否告知。。。
...全文
3158 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
舟中夜起 2001-09-09
  • 打赏
  • 举报
回复
BTW: int timeout
舟中夜起 2001-09-09
  • 打赏
  • 举报
回复
timeout = 5000;//ms
nRet = setsockopt(s,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout, sizeof(timeout));
jianweiweng 2001-09-08
  • 打赏
  • 举报
回复
如何触发超时机制呢?
舟中夜起 2001-06-21
  • 打赏
  • 举报
回复
查一下microsoft站点,里面对此有详细说明
舟中夜起 2001-06-21
  • 打赏
  • 举报
回复
你看msdn中的ping例子,里面就没有设置重叠方式
gPolaris 2001-06-21
  • 打赏
  • 举报
回复
这可不是BUG,socket默认是重叠方式,而用WSASocket必须自己指定参数,
怎么能说是WSASocket的bug呢?用法而已

重叠socket不在乎该socket是阻塞还是不阻塞的(Blocking),也就是overlap与blocking无关,你要设置超时,只有重叠socket支持这个功能,所以就会出现才开始的情况
舟中夜起 2001-06-21
  • 打赏
  • 举报
回复
up
舟中夜起 2001-06-20
  • 打赏
  • 举报
回复
请教overlapped和阻塞的区别是什么?难道就是两种不同的定义?谢谢
kock 2001-06-20
  • 打赏
  • 举报
回复
socket() 默认是OVERLAP的,见其帮助.
舟中夜起 2001-06-20
  • 打赏
  • 举报
回复
找到原因了,这是WSASocket的一个bug,如要设置timeout,必须把最后一个参数设置为
WSA_FLAG_OVERLAPPED

唉,没想到platform sdk的例程也有错误。

BTW:目前网络上的ping例子都有类似错误
舟中夜起 2001-06-20
  • 打赏
  • 举报
回复
我把WSASocket (AF_INET,SOCK_RAW,IPPROTO_ICMP,NULL, 0,0)
换成
socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);

就可以,但是为什么?
lts 2001-06-20
  • 打赏
  • 举报
回复
怎么不管用,
我的程序里就是这样写的
int timeout = 150000;
setsockopt(m_hSocket,SOL_SOCKET,SO_RCVTIMEO,(char *)&timeout,sizeof(int));
就有用。
// ping.cpp : Defines the entry point for the console application. // #pragma pack(4) #include "winsock2.h" #include "stdlib.h" #include "stdio.h" #define ICMP_ECHO 8 #define ICMP_ECHOREPLY 0 #define ICMP_MIN 8 // minimum 8 byte icmp packet (just header) /* The IP header */ typedef struct iphdr { unsigned int h_len:4; // length of the header unsigned int version:4; // Version of IP unsigned char tos; // Type of service unsigned short total_len; // total length of the packet unsigned short ident; // unique identifier unsigned short frag_and_flags; // flags unsigned char ttl; unsigned char proto; // protocol (TCP, UDP etc) unsigned short checksum; // IP checksum unsigned int sourceIP; unsigned int destIP; }IpHeader; // // ICMP header // typedef struct icmphdr { BYTE i_type; BYTE i_code; /* type sub code */ USHORT i_cksum; USHORT i_id; USHORT i_seq; /* This is not the std header, but we reserve space for time */ ULONG timestamp; }IcmpHeader; #define STATUS_FAILED 0xFFFF #define DEF_PACKET_SIZE 32 #define DEF_PACKET_NUMBER 4 /* 发送数据报的个数 */ #define MAX_PACKET 1024 #define xmalloc(s) HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,(s)) #define xfree(p) HeapFree (GetProcessHeap(),0,(p)) void fill_icmp_data(char *, int); USHORT checksum(USHORT *, int); int decode_resp(char *,int ,struct sockaddr_in *); void Usage(char *progname){ fprintf(stderr,"Usage:\n"); fprintf(stderr,"%s [number of packets] [data_size]\n",progname); fprintf(stderr,"datasize can be up to 1Kb\n"); ExitProcess(STATUS_FAILED); } int main(int argc, char **argv){ WSADATA wsaData; SOCKET sockRaw; struct sockaddr_in dest,from; struct hostent * hp; int bread,datasize,times; int fromlen = sizeof(from); int timeout = 1000; int statistic = 0; /* 用于统计结果 */ char *dest_ip; char *icmp_data; char *recvbuf; unsigned int addr=0; USHORT seq_no = 0; if (WSAStartup(MAKEWORD(2,1),&wsaData) != 0){ fprintf(stderr,"WSAStartup failed: %d\n",GetLastError()); ExitProcess(STATUS_FAILED); } if (argc <2 ) { Usage(argv[0]); } sockRaw = WSASocket(AF_INET,SOCK_RAW,IPPROTO_ICMP,NULL, 0,WSA_FLAG_OVERLAPPED); // //注:为了使用发送接收超时设置(即设置SO_RCVTIMEO, SO_SNDTIMEO), // 必须将标志位设为WSA_FLAG_OVERLAPPED ! // if (sockRaw == INVALID_SOCKET) { fprintf(stderr,"WSASocket() failed: %d\n",WSAGetLastError()); ExitProcess(STATUS_FAILED); } bread = setsockopt(sockRaw,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout, sizeof(timeout)); if(bread == SOCKET_ERROR) { fprintf(stderr,"failed to set recv timeout: %d\n",WSAGetLastError()); ExitProcess(STATUS_FAILED); } timeout = 1000; bread = setsockopt(sockRaw,SOL_SOCKET,SO_SNDTIMEO,(char*)&timeout, sizeof(timeout)); if(bread == SOCKET_ERROR) { fprintf(stderr,"failed to set send timeout: %d\n",WSAGetLastError()); ExitProcess(STATUS_FAILED); } memset(&dest,0,sizeof(dest)); hp = gethostbyname(argv[1]); if (!hp){ addr = inet_addr(argv[1]); } if ((!hp) && (addr == INADDR_NONE) ) { fprintf(stderr,"Unable to resolve %s\n",argv[1]); ExitProcess(STATUS_FAILED); } if (hp != NULL) memcpy(&(dest.sin_addr),hp->h_addr,hp->h_length); else dest.sin_addr.s_addr = addr; if (hp) dest.sin_family = hp->h_addrtype; else dest.sin_family = AF_INET; dest_ip = inet_ntoa(dest.sin_addr); // // atoi函数原型是: int atoi( const char *string ); // The return value is 0 if the input cannot be converted to an integer ! // if(argc>2) { times=atoi(argv[2]); if(times == 0) times=DEF_PACKET_NUMBER; } else times=DEF_PACKET_NUMBER; if (argc >3) { datasize = atoi(argv[3]); if (datasize == 0) datasize = DEF_PACKET_SIZE; if (datasize >1024) /* 用户给出的数据包大小太大 */ { fprintf(stderr,"WARNING : data_size is too large !\n"); datasize = DEF_PACKET_SIZE; } } else datasize = DEF_PACKET_SIZE; datasize += sizeof(IcmpHeader); icmp_data = (char*)xmalloc(MAX_PACKET); recvbuf = (char*)xmalloc(MAX_PACKET); if (!icmp_data) { fprintf(stderr,"HeapAlloc failed %d\n",GetLastError()); ExitProcess(STATUS_FAILED); } memset(icmp_data,0,MAX_PACKET); fill_icmp_data(icmp_data,datasize); // //显示提示信息 // fprintf(stdout,"\nPinging %s ....\n\n",dest_ip); for(int i=0;i<times;i++){ int bwrote; ((IcmpHeader*)icmp_data)->i_cksum = 0; ((IcmpHeader*)icmp_data)->timestamp = GetTickCount(); ((IcmpHeader*)icmp_data)->i_seq = seq_no++; ((IcmpHeader*)icmp_data)->i_cksum = checksum((USHORT*)icmp_data,datasize); bwrote = sendto(sockRaw,icmp_data,datasize,0,(struct sockaddr*)&dest,sizeof(dest)); if (bwrote == SOCKET_ERROR){ if (WSAGetLastError() == WSAETIMEDOUT) { printf("Request timed out.\n"); continue; } fprintf(stderr,"sendto failed: %d\n",WSAGetLastError()); ExitProcess(STATUS_FAILED); } if (bwrote < datasize ) { fprintf(stdout,"Wrote %d bytes\n",bwrote); } bread = recvfrom(sockRaw,recvbuf,MAX_PACKET,0,(struct sockaddr*)&from,&fromlen); if (bread == SOCKET_ERROR){ if (WSAGetLastError() == WSAETIMEDOUT) { printf("Request timed out.\n"); continue; } fprintf(stderr,"recvfrom failed: %d\n",WSAGetLastError()); ExitProcess(STATUS_FAILED); } if(!decode_resp(recvbuf,bread,&from)) statistic++; /* 成功接收的数目++ */ Sleep(1000); } /* Display the statistic result */ fprintf(stdout,"\nPing statistics for %s \n",dest_ip); fprintf(stdout," Packets: Sent = %d,Received = %d, Lost = %d (%2.0f%% loss)\n",times, statistic,(times-statistic),(float)(times-statistic)/times*100); WSACleanup(); return 0; } /* The response is an IP packet. We must decode the IP header to locate the ICMP data */ int decode_resp(char *buf, int bytes,struct sockaddr_in *from) { IpHeader *iphdr; IcmpHeader *icmphdr; unsigned short iphdrlen; iphdr = (IpHeader *)buf; iphdrlen = (iphdr->h_len) * 4 ; // number of 32-bit words *4 = bytes if (bytes < iphdrlen + ICMP_MIN) { printf("Too few bytes from %s\n",inet_ntoa(from->sin_addr)); } icmphdr = (IcmpHeader*)(buf + iphdrlen); if (icmphdr->i_type != ICMP_ECHOREPLY) { fprintf(stderr,"non-echo type %d recvd\n",icmphdr->i_type); return 1; } if (icmphdr->i_id != (USHORT)GetCurrentProcessId()) { fprintf(stderr,"someone else''s packet!\n"); return 1; } printf("%d bytes from %s:",bytes, inet_ntoa(from->sin_addr)); printf(" icmp_seq = %d. ",icmphdr->i_seq); printf(" time: %d ms ",GetTickCount()-icmphdr->timestamp); printf("\n"); return 0; } USHORT checksum(USHORT *buffer, int size) { unsigned long cksum=0; while(size >1) { cksum+=*buffer++; size -=sizeof(USHORT); } if(size) { cksum += *(UCHAR*)buffer; } cksum = (cksum >> 16) + (cksum & 0xffff); cksum += (cksum >>16); return (USHORT)(~cksum); } /* Helper function to fill in various stuff in our ICMP request. */ void fill_icmp_data(char * icmp_data, int datasize){ IcmpHeader *icmp_hdr; char *datapart; icmp_hdr = (IcmpHeader*)icmp_data; icmp_hdr->i_type = ICMP_ECHO; icmp_hdr->i_code = 0; icmp_hdr->i_id = (USHORT)GetCurrentProcessId(); icmp_hdr->i_cksum = 0; icmp_hdr->i_seq = 0; datapart = icmp_data + sizeof(IcmpHeader); // // Place some junk in the buffer. // memset(datapart,''E'', datasize - sizeof(IcmpHeader)); }
#pragma pack(4) //#include "stdafx.h" #pragma comment (lib,"Ws2_32.lib") #define WIN32_LEAN_AND_MEAN #include #include #include #include #include #include #include typedef struct iphdr { unsigned int headlen:4; unsigned int version:4; unsigned char tos; unsigned short totallen; unsigned short id; unsigned short falg; unsigned char ttl; unsigned char prot; unsigned short checksum; unsigned int sourceIP; unsigned int destIP; }IpHeader; typedef struct icmphdr { BYTE type; BYTE code; USHORT checksum; USHORT id; USHORT seg; }IcmpHeader; #define ICMP_RCHO 8 #define ICMP_RCHO_REPLY 0 #define ICMP_MIN 8 #define STATUS_FAILED 0xFFFF #define DEF_PACKET_SIZE 32 #define MAX_PACKET 1024 #define MAX_PING_PACKET_SIZE (MAX_PACKET+sizeof(IpHeader)) void fill_icmp_data(char *,int); USHORT checksum(USHORT *,int); void decode_resp(char *,int,struct sockaddr_in *); DWORD WINAPI FindIP(LPVOID pIPAddrTemp); WSADATA wsaData; SOCKET sockRaw; struct sockaddr_in dest,from,end; int fromlen =sizeof(from); char *recvbuf=new char[MAX_PING_PACKET_SIZE]; unsigned int addr=0; long ThreadNumCounter=0,ThreadNumLimit=20; long *aa=&ThreadNumCounter; void main(int argc,char *argv[]) { /*if(argc!=3) { cout<<"输入格式错误: start_ip end_ip"<Socket(AF_INET,SOCK_RAW,IPPROTO_ICMP,NULL,0,WSA_FLAG_OVERLAPPED); if(sockRaw==INVALID_SOCKET) { cout<<"WASSocketet() falied"<timeout=1000; int bread=setsockopt(sockRaw,SOL_SOCKET,SO_RCVTIMEO,(char *)&timeout,sizeof(timeout)); if(bread==SOCKET_ERROR) { cout<<"FAILED TO SEY RECV TIMEOUT"<timeout=1000; bread=setsockopt(sockRaw,SOL_SOCKET,SO_SNDTIMEO,(char *)&timeout,sizeof(timeout)); if(bread==SOCKET_ERROR) { cout<<"FAILED TO SEY RECV TIMEOUT"<set(&dest,0,sizeof(dest)); unsigned long startIP,endIP; dest.sin_family=AF_INET; dest.sin_addr.s_addr=inet_addr(argv[1]); startIP=inet_addr(argv[1]); end.sin_family=AF_INET; end.sin_addr.s_addr=inet_addr(argv[2]); endIP=inet_addr(argv[2]); HANDLE hThread; while(htonl(startIP)ThreadNumLimit) { Sleep(5000); continue; } DWORD ThreadID; sockaddr_in *pIPAddrTemp=new (sockaddr_in); if(!pIPAddrTemp) { cout<<"memory alloc failed"<set(&from,0,sizeof(from)); startIP=htonl(htonl(startIP)+1); dest.sin_addr.s_addr=startIP; } while(ThreadNumCounter!=0) { Sleep(2000); return; cout<<"error"id=(USHORT)GetCurrentThreadId(); datapart=icmp_data+sizeof(IcmpHeader); memset(datapart,'A',datasize-sizeof(IcmpHeader)); } void decode_resp(char *buf,int bytes,struct sockaddr_in *from) { IpHeader *iphdr; IcmpHeader *icmphdr; unsigned short iphdrlen; iphdr=(IpHeader*) buf; iphdrlen=iphdr->headlen*4; icmphdr=(IcmpHeader *)(buf+iphdrlen); if(bytestype!=ICMP_RCHO_REPLY)return; if(icmphdr->id!=(USHORT)GetCurrentThreadId())return; cout<<"活动主机: "<CHAR*)buffer; } cksum=(cksum>>16)+(cksum& 0xffff); cksum+=(cksum>>16); return (USHORT)(~cksum); } DWORD WINAPI FindIP(LPVOID pIPAddrTemp) { InterlockedIncrement(aa); char icmp_data[MAX_PACKET]; memset(icmp_data,0,MAX_PACKET); int datasize=DEF_PACKET_SIZE; datasize+=sizeof(IcmpHeader); fill_icmp_data(icmp_data,datasize); ((IcmpHeader*)icmp_data)->checksum=0; ((IcmpHeader*)icmp_data)->seg=0; ((IcmpHeader*)icmp_data)->checksum=checksum((USHORT*)icmp_data,datasize); int bwrote=sendto(sockRaw,icmp_data,datasize,0,(struct sockaddr *)pIPAddrTemp,sizeof(dest)); int n=0; if(bwrote==SOCKET_ERROR) { if(WSAGetLastError()==WSAETIMEDOUT) { cout<<"timed out"<TIMEDOUT) { cout<<"timed out"<recvfrom(sockRaw,recvbuf,MAX_PING_PACKET_SIZE,0,(struct sockaddr *)&from,&fromlen); if(bread==SOCKET_ERROR) { if(WSAGetLastError()==WSAETIMEDOUT) { cout<<"timed out"<recvfrom falied"<recvbuf,bread,&from); InterlockedDecrement(aa); } return 0; }
// ipmonDlg.cpp : implementation file // #include "stdafx.h" #include "ipmon.h" #include "ipmonDlg.h" #include "mstcpip.h" #include "afxsock.h" #include "Iphlpapi.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About PROTN2T aOfProto [ PROTO_NUM + 1] = { { IPPROTO_IP , "IP" }, { IPPROTO_ICMP , "ICMP" }, { IPPROTO_IGMP , "IGMP" }, { IPPROTO_GGP , "GGP" }, { IPPROTO_TCP , "TCP" }, { IPPROTO_PUP , "PUP" }, { IPPROTO_UDP , "UDP" }, { IPPROTO_IDP , "IDP" }, { IPPROTO_ND , "NP" }, { IPPROTO_RAW , "RAW" }, { IPPROTO_MAX , "MAX" }, { NULL , "" } } ; char *get_proto_name( unsigned char proto ) { BOOL bFound = FALSE ; for( int i = 0 ; i < PROTO_NUM ; i++ ) { if( aOfProto[i].proto == proto ) { bFound = TRUE ; break ; } } if( bFound ) return aOfProto[i].pprototext ; return aOfProto[PROTO_NUM].pprototext ; } 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() ///////////////////////////////////////////////////////////////////////////// // CIpmonDlg dialog CIpmonDlg::CIpmonDlg(CWnd* pParent /*=NULL*/) : CDialog(CIpmonDlg::IDD, pParent) { //{{AFX_DATA_INIT(CIpmonDlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); m_threadID = 0 ; m_Multihomed = FALSE ; m_Local = TRUE ; } void CIpmonDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CIpmonDlg) DDX_Control(pDX, IDC_LIST, m_ctrList); DDX_Control(pDX, IDC_LOOKUP, m_start); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CIpmonDlg, CDialog) //{{AFX_MSG_MAP(CIpmonDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_LOOKUP, OnLookUp) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CIpmonDlg message handlers BOOL CIpmonDlg::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 // TODO: Add extra initialization here CHAR szHostName[128] = {0}; HOSTENT* pHost = NULL; CHAR* pszIp = NULL; int iNum = 0; if(AfxSocketInit(NULL)==FALSE) { AfxMessageBox("Sorry, socket load error!"); return FALSE; } if(gethostname(szHostName, 128)==0) { pHost = gethostbyname(szHostName); if(pHost != NULL) { pszIp = inet_ntoa(*(in_addr*)pHost->h_addr_list[iNum]); m_ipsource = inet_addr(pszIp); } else AfxMessageBox("pHost = NULL!"); } else AfxMessageBox("can't find host name!"); // ListView initialize DWORD dwStyle=GetWindowLong(m_ctrList.GetSafeHwnd(),GWL_STYLE); dwStyle&=~LVS_TYPEMASK; dwStyle|=LVS_REPORT; SetWindowLong(m_ctrList.GetSafeHwnd(),GWL_STYLE,dwStyle); m_ctrList.InsertColumn(0,"数据",LVCFMT_LEFT,525); m_ctrList.InsertColumn(0,"大小",LVCFMT_LEFT,80); m_ctrList.InsertColumn(0,"端口",LVCFMT_LEFT,40); m_ctrList.InsertColumn(0,"目的地址",LVCFMT_LEFT,100); m_ctrList.InsertColumn(0,"端口",LVCFMT_LEFT,40); m_ctrList.InsertColumn(0,"源地址",LVCFMT_LEFT,100); m_ctrList.InsertColumn(0,"协议",LVCFMT_LEFT,50); ::SendMessage(m_ctrList.m_hWnd, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_FULLROWSELECT, LVS_EX_FULLROWSELECT); // Here read all IPs of this host DWORD dwSize = 0 ; GetIpAddrTable( NULL , &dwSize, FALSE ) ; PMIB_IPADDRTABLE pIpAddrTable = (PMIB_IPADDRTABLE )new BYTE [ dwSize ] ; if( pIpAddrTable ) { if( GetIpAddrTable( (PMIB_IPADDRTABLE)pIpAddrTable, // // buffer for IP table &dwSize, // size of buffer FALSE // sort by IP address ) == NO_ERROR ) { if( pIpAddrTable->dwNumEntries > 2 ) // Second is MS TCP loopback IP ( 127.0.0.1 ) { m_Multihomed = TRUE ; char szIP[16]; for( int i = 0 ; i < (int)pIpAddrTable->dwNumEntries ; i++ ) { in_addr ina ; ina.S_un.S_addr = pIpAddrTable->table[i].dwAddr ; char *pIP = inet_ntoa( ina ) ; strcpy( szIP , pIP ) ; if( stricmp( szIP , "127.0.0.1" ) ) m_IPArr.Add(pIpAddrTable->table[i].dwAddr) ; } } } delete [] pIpAddrTable ; } return TRUE; // return TRUE unless you set the focus to a control } void CIpmonDlg::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 CIpmonDlg::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 CIpmonDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } UINT threadFunc ( LPVOID p ) { CIpmonDlg *pDlg = static_cast(p) ; char buf [1000] , *bufwork ; MSG msg ; int iRet ; DWORD dwErr ; char *pSource , *pDest ; IPHEADER *pIpHeader ; in_addr ina ; char szSource [16] , szDest[16] , szErr [ 50 ]; char *pLastBuf = NULL ; int HdrLen, totallen; WORD sourport, destport; struct TCPPacketHead *pTCPHead; struct ICMPPacketHead *pICMPHead; struct UDPPacketHead *pUDPHead; BYTE *pdata = NULL; /*---------------------------------------------------------------------*/ PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE) ; // Force to make the queue pDlg->m_threadID = GetCurrentThreadId() ; while( TRUE ) { if( PeekMessage( &msg , 0 , WM_CLOSE,WM_CLOSE,PM_NOREMOVE ) ) { closesocket( pDlg->m_s ) ; pDlg->m_threadID = 0 ; pDlg->m_start.EnableWindow(TRUE) ; break ; } memset( buf , 0 , sizeof(buf) ) ; iRet = recv( pDlg->m_s , buf , sizeof( buf ) , 0 ) ; if( iRet == SOCKET_ERROR ) { dwErr = WSAGetLastError() ; sprintf( szErr , "Error recv() = %ld " , dwErr ) ; continue ; } else if( *buf ) { bufwork = buf ; pIpHeader = (IPHEADER *)bufwork ; WORD iLen = ntohs(pIpHeader->total_len) ; while( TRUE ) { if( iLen <= iRet ) { ina.S_un.S_addr = pIpHeader->sourceIP ; pSource = inet_ntoa( ina ) ; strcpy( szSource , pSource ) ; ina.S_un.S_addr = pIpHeader->destIP ; pDest = inet_ntoa( ina ) ; strcpy( szDest , pDest ) ; CString str, strProto, strSourPort, strDestPort, strData, strSize; strProto = get_proto_name( pIpHeader->proto ); /*-------------------zhuwei add(2002.11.9)-----------------------------*/ HdrLen = pIpHeader->header_len&0xf; HdrLen *= 4; totallen = ntohs(pIpHeader->total_len); totallen-=HdrLen; switch(pIpHeader->proto) { case IPPROTO_ICMP: { pICMPHead=(struct ICMPPacketHead *)(buf+HdrLen); //strL4.Format(" type:%d code:%d\n",pICMPHead->Type,pICMPHead->Code); strSourPort = "-"; strDestPort = "-"; pdata=((BYTE *)pICMPHead)+ICMP_HEAD_LEN; totallen -= ICMP_HEAD_LEN; break; } case IPPROTO_TCP: { pTCPHead=(struct TCPPacketHead *)(buf+HdrLen); sourport = ntohs(pTCPHead->SourPort); destport = ntohs(pTCPHead->DestPort); //strL4.Format(" sour port:%d,dest port:%d",sourport,destport); strSourPort.Format("%d",sourport); strDestPort.Format("%d",destport); HdrLen = (pTCPHead->HLen)>>4; //in fact only 4 bits HdrLen *= 4; pdata=((BYTE *)pTCPHead)+HdrLen; totallen -= HdrLen; break; } case IPPROTO_UDP: { pUDPHead=(struct UDPPacketHead *)(buf+HdrLen); sourport = ntohs(pUDPHead->SourPort); destport = ntohs(pUDPHead->DestPort); //strL4.Format(" sour port:%d,dest port:%d",sourport,destport); strSourPort.Format("%d",sourport); strDestPort.Format("%d",destport); pdata=((BYTE *)pUDPHead)+UDP_HEAD_LEN; totallen -= UDP_HEAD_LEN; break; } } if(pIpHeader->proto == IPPROTO_ICMP) strData.Format("type:%d code:%d data:%s",pICMPHead->Type,pICMPHead->Code,pdata); else strData.Format(" %s",pdata); strSize.Format("%d",totallen); pDlg->AddData(strProto,szSource,strSourPort,szDest,strDestPort,strSize,strData); if( iLen < iRet ) { iRet -= iLen ; bufwork += iLen ; pIpHeader = (IPHEADER *)bufwork ; } else break ; // pIpHeader->total_len == iRet and go out } else { // read last part of buf. I wrote it , but always recv() read exactly // the lenght of the packet int iLast = iLen - iRet ; pLastBuf = new char [ iLen ] ; int iReaden = iRet ; memcpy( pLastBuf , bufwork , iReaden ) ; iRet = recv( pDlg->m_s , pLastBuf + iReaden , iLast , 0 ) ; if( iRet == SOCKET_ERROR ) { dwErr = WSAGetLastError() ; sprintf( szErr , "Error recv() = %ld " , dwErr ) ; break ; } else { bufwork = pLastBuf ; pIpHeader = (IPHEADER *)bufwork ; if( iRet == iLast ) iRet = iLen ; else { // read all last data iReaden += iRet ; iLast -= iRet ; while( TRUE ) { iRet = recv( pDlg->m_s , pLastBuf +iReaden , iLast , 0 ) ; if( iRet == SOCKET_ERROR ) { dwErr = WSAGetLastError() ; sprintf( szErr , "Error recv() = %ld " , dwErr ) ; break ; } else { iReaden += iRet ; iLast -= iRet ; if( iLast <= 0 ) break ; } } // while } } } } // while if( pLastBuf ) delete [ ] pLastBuf ; } else { AfxMessageBox( "No data on network" ) ; continue ; } } return TRUE ; } void CIpmonDlg::OnLookUp() { // TODO: Add your control notification handler code here char szErr [ 50 ] , szHostName[MAX_PATH]; DWORD dwErr ; SOCKADDR_IN sa; gethostname(szHostName, sizeof(szHostName)) ; m_iphostsource = m_ipsource ; m_ipcheckedhost = ntohl(m_iphost) ; if( 0 == m_threadID ) { SetDlgItemText(IDC_LOOKUP,"停止查看!" ); } else { if( m_threadID ) { PostThreadMessage(m_threadID,WM_CLOSE,0,0) ; SetDlgItemText(IDC_LOOKUP,"开始查看!"); m_start.EnableWindow(FALSE) ; } return ; } DWORD dwBufferLen[10] ; DWORD dwBufferInLen= 1 ; DWORD dwBytesReturned = 0 ; m_s = socket( AF_INET , SOCK_RAW , IPPROTO_IP ) ; if( INVALID_SOCKET == m_s ) { dwErr = WSAGetLastError() ; sprintf( szErr , "Error socket() = %ld " , dwErr ) ; AfxMessageBox( szErr ) ; closesocket( m_s ) ; return ; } int rcvtimeo = 5000 ; if( setsockopt( m_s , SOL_SOCKET , SO_RCVTIMEO , (const char *)&rcvtimeo , sizeof(rcvtimeo) ) == SOCKET_ERROR) { dwErr = WSAGetLastError() ; sprintf( szErr , "Error WSAIoctl = %ld " , dwErr ) ; AfxMessageBox( szErr ) ; closesocket( m_s ) ; return ; } sa.sin_family = AF_INET; sa.sin_port = htons(7000); sa.sin_addr.s_addr= m_iphostsource; if (bind(m_s,(PSOCKADDR)&sa, sizeof(sa)) == SOCKET_ERROR) { dwErr = WSAGetLastError() ; sprintf( szErr , "Error bind() = %ld " , dwErr ) ; AfxMessageBox( szErr ) ; closesocket( m_s ) ; return ; } if( SOCKET_ERROR != WSAIoctl( m_s, SIO_RCVALL , &dwBufferInLen, sizeof(dwBufferInLen), &dwBufferLen, sizeof(dwBufferLen), &dwBytesReturned , NULL , NULL ) ) AfxBeginThread( threadFunc , (LPVOID)this ); else { dwErr = WSAGetLastError() ; sprintf( szErr , "Error WSAIoctl = %ld " , dwErr ) ; AfxMessageBox( szErr ) ; closesocket( m_s ) ; return ; } } void CIpmonDlg::OnOK() { // TODO: Add extra validation here if( NULL != m_threadID ) PostThreadMessage(m_threadID,WM_CLOSE,0,0) ; if( m_IPArr.GetSize() ) m_IPArr.RemoveAll() ; CDialog::OnOK(); } void CIpmonDlg::AddData(CString s0,CString s1, CString s2, CString s3, CString s4, CString s5, CString s6) { int index; index = m_ctrList.InsertItem(0,s0); m_ctrList.SetItem(index,1,LVIF_TEXT,s1, 0, 0, 0,0); m_ctrList.SetItem(index,2,LVIF_TEXT,s2, 0, 0, 0,0); m_ctrList.SetItem(index,3,LVIF_TEXT,s3, 0, 0, 0,0); m_ctrList.SetItem(index,4,LVIF_TEXT,s4, 0, 0, 0,0); m_ctrList.SetItem(index,5,LVIF_TEXT,s5, 0, 0, 0,0); m_ctrList.SetItem(index,6,LVIF_TEXT,s6, 0, 0, 0,0); }

16,472

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧