
/*
#include #pragma comment(lib,"WS2_32.lib") */ WSADATA wsd; static UINT port=%%1; UINT Listen(LPVOID pParam) { SOCKET sServer,sClient; char buf[1024]; int retVal; if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { return -1;//失败 } sServer=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(INVALID_SOCKET==sServer) { WSACleanup(); return -1;//创建套接字失败 } SOCKADDR_IN addrServ; addrServ.sin_family=AF_INET; addrServ.sin_port=htons((short)pParam); addrServ.sin_addr.s_addr=INADDR_ANY; retVal=bind(sServer,(LPSOCKADDR)&addrServ,sizeof(SOCKADDR_IN)); if(SOCKET_ERROR==retVal) { closesocket(sServer); WSACleanup(); return -1;//绑定套接字失败 } retVal=listen(sServer,1); if(SOCKET_ERROR==retVal) { closesocket(sServer); WSACleanup(); return -1;//开始监听失败 } sockaddr_in addrClient; int addrClientlen=sizeof(addrClient); sClient=accept(sServer,(sockaddr FAR*)&addrClient,&addrClientlen); if(INVALID_SOCKET==sClient) { closesocket(sServer); WSACleanup(); return -1;//开始接受客户端连接失败 } ZeroMemory(buf,sizeof(buf)); retVal=recv(sClient,buf,sizeof(buf),0); if(SOCKET_ERROR==retVal) { closesocket(sServer); closesocket(sClient); WSACleanup(); \f return -1;//接收数据失败 } CString %%2(buf); closesocket(sServer); closesocket(sClient); WSACleanup(); return 0; } CWinThread *pThread=AfxBeginThread(Listen,&port); 2.简单客户端 /* #include #pragma comment(lib,"WS2_32.lib") */ WSADATA wsd; SOCKET sHost; SOCKADDR_IN servAddr; char buf[1024]; int retVal; if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { return -1;//失败 } sHost=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(INVALID_SOCKET==sHost) { WSACleanup(); return -1;//创建套接字失败 } servAddr.sin_family=AF_INET; servAddr.sin_addr.s_addr=inet_addr(%%3); servAddr.sin_port=htons((short)%%2); int nServAddlen=sizeof(servAddr); retVal=connect(sHost,(LPSOCKADDR)&servAddr,sizeof(servAddr)); if(SOCKET_ERROR==retVal) { closesocket(sHost); WSACleanup(); return -1;//连接服务器失败 } ZeroMemory(buf,sizeof(buf)); strcpy(buf,%%3); retVal=send(sHost,buf,sizeof(buf),0); if(SOCKET_ERROR==retVal) { closesocket(sHost); WSACleanup(); return -1;//向服务器发送数据失败 } closesocket(sHost); WSACleanup(); 3.获得本机IP /* #include #pragma comment(lib,"WS2_32.lib") \f */ WSADATA wsd; if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { return -1;//失败 } char szHostname[100],szHostaddress[200]; if(gethostname(szHostname,sizeof(szHostname))!=SOCKET_ERROR) { HOSTENT *pHostEnt=gethostbyname(szHostname); if(pHostEnt!=NULL){ sprintf(szHostaddress,"%d.%d.%d.%d )); } } else return; CString %%1(szHostaddress); 4.端对端通信 /* #include #pragma comment(lib,"WS2_32.lib") */ WSADATA wsd; SOCKET s; char buf[1024]; if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { return -1;//失败 } s=socket(AF_INET,SOCK_DGRAM,0); if(s==INVALID_SOCKET) { WSACleanup(); return -1;//创建套接字失败 } SOCKADDR_IN servAddr; servAddr.sin_family=AF_INET; servAddr.sin_addr.s_addr=inet_addr(%%1); servAddr.sin_port=htons(INADDR_ANY); if(bind(s,(SOCKADDR*)&servAddr,sizeof(SOCKADDR_IN))==SOCKET_ERROR) { closesocket(s); WSACleanup(); return -1;//绑定套接字失败 } int nServAddrlen=sizeof(servAddr); ZeroMemory(buf,sizeof(buf)); if(recvfrom(s,buf,sizeof(buf),0,(SOCKADDR*)&servAddr,&nServAddrlen)==SOCKET_ERROR) { closesocket(s); WSACleanup(); \f return -1;//接收数据失败 } CString %%2(buf); ZeroMemory(buf,sizeof(buf)); strcpy(buf,%%3); SOCKADDR_IN clientAddr; clientAddr.sin_family=AF_INET; clientAddr.sin_addr.s_addr=inet_addr(%%4); clientAddr.sin_port=htons((short)%%5); int nClientlen=sizeof(clientAddr); if(sendto(s,buf,sizeof(buf),0,(SOCKADDR*)&clientAddr,nClientlen)==SOCKET_ERROR) { closesocket(s); WSACleanup(); return -1;//向服务器发送数据失败 } closesocket(s); WSACleanup(); 5.点对点通信 /* #include #pragma comment(lib,"WS2_32.lib") */ WSADATA wsd; SOCKADDR_IN addrServ,addrServ2; SOCKET sServer,sClient,sHost; int retVal; sockaddr_in addrClient; char buf[1024]; static UINT port=%%2; BOOL listenerRun=TRUE; UINT Listen(LPVOID pParam) { addrServ.sin_family=AF_INET; addrServ.sin_port=htons((UINT)pParam); addrServ.sin_addr.s_addr=INADDR_ANY; retVal=bind(sServer,(LPSOCKADDR)&addrServ,sizeof(SOCKADDR_IN)); if(SOCKET_ERROR==retVal) { closesocket(sServer); WSACleanup(); return -1;//绑定套接字失败 } retVal=listen(sServer,1); if(SOCKET_ERROR==retVal) { closesocket(sServer); WSACleanup(); return -1;//开始监听失败 } int addrClientlen=sizeof(addrClient); sClient=accept(sServer,(sockaddr FAR*)&addrClient,&addClientlen); if(INVALID_SOCKET==sClient) { closesocket(sServer); \f WSACleanup(); return -1;//接收客戶端请求失败 } while(listenerRun) { ZeroMemory(buf,sizeof(buf)); retVal=recv(sClient,buf,sizeof(buf)); if(SOCKET_ERROR==retVal) { closesocket(sServer); closesocket(sClient); WSACleanup(); return -1;//接收客户端数据失败 } CString %%4(buf); } } if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { return -1;//失败 } sServer=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(INVALID_SOCKET==sServer) { WSACleanup(); return -1;//创建套接字失败 } CWinThread *pThread=AfxBeginThread(Listen,&port); sHost=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(INVALID_SOCKET==sHost) { WSACleanup(); return -1;//创建套接字失败 } servAddr2.sin_family=AF_ INET; servAddr2.sin_addr.s_addr=inet_addr(%%1); servAddr.sin_port=htons((short)%%3); int nServerAddrlen=sizeof(servAddr2); retVal=connect(sHost,(LPSOCKADDR)&servAddr2,sizeof(servAddr2)); if(SOCKET_ERROR==retVal) { closesocket(sHost); WSACleanup(); return -1;//连接失败 } zeroMemory(buf,sizeof(buf)); strcpy(buf,%%5); retVal=send(sHost,buf,sizeof(buf),0); if(SOCKET_ERROR==retVal) { closesocket(sHost); WSACleanup(); return -1;//向发送数据失败 } listenerRun=FALSE; DWORD dwExitCode; \f ::GetExitCodeThread(pThread->m_hThread,&dwExitCode); pThread=null; closesocket(sServer); closesocket(sClient); closesocket(sHost); WSACleanup(); 6.UDP对时服务器端 /* #include #pragma comment(lib,"WS2_32.lib") */ WSADATA wsd; SOCKET s; char buf[1024]; if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { return -1;//失败 } s=socket(AF_INET,SOCK_DGRAM,0); if(s==INVALID_SOCKET) { WSACleanup(); return -1;//创建套接字失败 } SOCKADDR_IN servAddr; servAddr.sin_family=AF_INET; servAddr.sin_addr.s_addr=inet_addr("127.0.0.1"); servAddr.sin_port=htons(5000); if(bind(s,(SOCKADDR*)&servAddr,sizeof(SOCKADDR_IN))==SOCKET_ERROR) { closesocket(s); WSACleanup(); return -1;//绑定套接字失败 } int nServAddrlen=sizeof(servAddr); ZeroMemory(buf,sizeof(buf)); if(recvfrom(s,buf,sizeof(buf),0,(SOCKADDR*)&servAddr,&nServAddrlen)==SOCKET_ERROR) { closesocket(s); WSACleanup(); return -1;//接收数据失败 } CString str(buf); if(str=="TimeNow") { SOCKADDR_IN clientAddr; clientAddr.sin_family=AF_INET; clientAddr.sin_addr.s_addr=inet_addr("127.0.0.1"); clientAddr.sin_port=htons((short)2000); int nClientlen=sizeof(clientAddr); SYSTEMTIME systime; GetLocalTime(&systime); if(sendto(s,(char *)&systime,sizeof(SYSTEMTIME),0,(SOCKADDR*)&clientAddr,nClientlen)==SOCKET_ERROR) { \f closesocket(s); WSACleanup(); return -1;//向服务器发送数据失败 } } closesocket(s); WSACleanup(); 7.UDP对时客户端 /* #include #pragma comment(lib,"WS2_32.lib") */ WSADATA wsd; SOCKET s; char buf[1024]; if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { return -1;//失败 } s=socket(AF_INET,SOCK_DGRAM,0); if(s==INVALID_SOCKET) { WSACleanup(); return -1;//创建套接字失败 } SOCKADDR_IN servAddr; servAddr.sin_family=AF_INET; servAddr.sin_addr.s_addr=inet_addr("127.0.0.1"); servAddr.sin_port=htons(2000); if(bind(s,(SOCKADDR*)&servAddr,sizeof(SOCKADDR_IN))==SOCKET_ERROR) { closesocket(s); WSACleanup(); return -1;//绑定套接字失败 } int nServAddrlen=sizeof(servAddr); ZeroMemory(buf,sizeof(buf)); CString ss="TimeNow"; strcpy(buf,ss); SOCKADDR_IN clientAddr; clientAddr.sin_family=AF_INET; clientAddr.sin_addr.s_addr=inet_addr("127.0.0.1"); clientAddr.sin_port=htons((short)5000); int nClientlen=sizeof(clientAddr); if(sendto(s,buf,sizeof(buf),0,(SOCKADDR*)& clientAddr,nClientlen)==SOCKET_ERROR) { closesocket(s); WSACleanup(); return -1;//向服务器发送数据失败 } memset(buf,0,1024); if(recvfrom(s,buf,sizeof(buf),0,(SOCKADDR*)&servAddr,&nServAddrlen)==SOCKET_ERROR) { closesocket(s); WSACleanup(); \f return -1;//接收数据失败 } SYSTEMTIME systime; memcpy(&systime,buf,16); SetLocalTime(&systime);//设置本地与服务器时间同步。 closesocket(s); WSACleanup(); 8.点对点传输文件 CFile myFile; if(!myFile.Open(Dlg.GetPathName(), CFile::modeRead | CFile::typeBinary)) { AfxMessageBox("文件不存在! ewMail->Body = _T("Put your message here"); spNewMail- >AttachFile(_variant_t(_bstr_t("C:\\\mp\\\est\\\\mail\\\\mail.cpp")),_variant_t((long)DISP_E_PARAMNOTFOUND , VT_ERROR),_variant_t((long)DISP_E_PARAMNOTFOUND, VT_ERROR)); spNewMail->Send(); printf("send ok"); } catch(_com_error &ComError) { printf("%s\ CSendDlg::OnDisconnect() { m_pTcpClient->Disconnect(); m_ctlCnnStatus.SetWindowText("断开连接"); } void CSendDlg::OnSendFile() { if(!UpdateData()) return; m_pTcpClient->SetPackageSize(m_dwPackageSize); if(!m_pTcpClient->SendFile((char *)(LPCTSTR)m_strFileName)) AfxMessageBox("发生文件失败"); } void CSendDlg::OnSendMsg(void) { char s[99999]; if(!UpdateData()) return; sprintf(s, "@00000001%s char *szPathName, BOOL bAllowUndo = FALSE); BOOL RenameFileEx(char *szOldPathName, char *szNewPathName); BOOL MoveFileEx(char *szSrcPathName, char *szDstPathName); BOOL CopyFileEx(char *szSrcPathName, char *szDstPathName); // 重新启动操作系统 BOOL RebootWindows(); // 设置程序是否在操作系统启动后自动运行 void SetAutoRun(BOOL bEnable); BOOL ShutDownWin98(); BOOL ShutDownWinNT(); BOOL IsLegalFileName(char *szFileName); m_pTcpServer1 = new CTcpServer(this); m_pTcpServer1->SetBindAddr(""); m_pTcpServer1->SetPort(8000); m_pTcpServer1->SetOnAccept(OnAccept); m_pTcpServer1->SetOnAcceptErr(OnAcceptErr); m_pTcpServer1->SetOnSocketConnect(OnSocketConnect); m_pTcpServer1->SetOnSocketDisconnect(OnSocketDisconnect); m_pTcpServer1->SetOnSocketSendErr(OnSocketSendErr); m_pTcpServer1->SetOnSocketRecvErr(OnSocketRecvErr); m_pTcpServer1->SetOnOneNetMsg(OnOneNetMsg); m_pTcpServer1->SetOnRecvFileStart(OnRecvFileStart); m_pTcpServer1->SetOnRecvFileProgress(OnRecvFileProgress); m_pTcpServer1->SetOnRecvFileFail(OnRecvFileFail); m_pTcpServer1->SetOnRecvFileSucc(OnRecvFileSucc); m_pTcpServer1->SetOnRecvFileCancel(OnRecvFileCancel); \f if(!m_pTcpServer1->StartAccept()) { AfxMessageBox("开始服务失败"); return FALSE; } void CRecvDlg::OnAccept(void *pNotifyObj, SOCKET hSocket, BOOL &bAccept) { CRecvDlg *pRecvDlg = (CRecvDlg *)pNotifyObj; CString strInfo; strInfo.Format("OnAccept-%d ); } void CRecvDlg::DispCnnCount(void) { CString strCnnCount; strCnnCount.Format("%d TcpClient->SetOnSendFileRefuseRecv(OnSendFileRefuseRecv); m_pTcpClient->SetOnSendFileCancelRecv(OnSendFileCancelRecv); \f m_pTcpClient->SetOnSendFileRecvFail(OnSendFileRecvFail); m_pTcpClient->SetOnSendFileProgress(OnSendFileProgress); CStatic m_ctlCnnStatus; CStatic m_ctlInfo; DWORD m_dwPackageSize; CString m_strServerIp; int m_nPort; CString m_strFileName; CString m_strMsg; void CSendDlg::OnConnect() { if(!UpdateData()) return; m_pTcpClient->SetAddr((char *)(LPCTSTR)m_strServerIp); m_pTcpClient->SetPort(m_nPort); m_pTcpClient->SetPackageSize(m_dwPackageSize); m_ctlCnnStatus.SetWindowText("请等待..."); if(!m_pTcpClient->Connect()) m_ctlCnnStatus.SetWindowText("连接失败!"); else m_ctlCnnStatus.SetWindowText("已连接"); } void CSendDlg::OnDisconnect() { m_pTcpClient->Disconnect(); m_ctlCnnStatus.SetWindowText("断开连接"); } void CSendDlg::OnSendFile() { if(!UpdateData()) return; m_pTcpClient->SetPackageSize(m_dwPackageSize); if(!m_pTcpClient->SendFile((char *)(LPCTSTR)m_strFileName)) AfxMessageBox("发生文件失败"); } void CSendDlg::OnSendMsg(void) { char s[99999]; if(!UpdateData()) return; sprintf(s, "@00000001%s "OnSendFileRecvFail"); } void CSendDlg::OnSendFileProgress(void *pNotifyObj, int nSentBytes, int nTotalBytes) { CSendDlg *pSendDlg = (CSendDlg *)pNotifyObj; CString strInfo; strInfo.Format("%d / %d RecvDlg *)pNotifyObj; CString strInfo; strInfo.Format("%d / %d Caps(hScrDC, VERTRES); //确保选定区域是可见的 if (nX <0) nX = 0; if (nY < 0) nY = 0; if (nX2 > xScrn) nX2 = xScrn; if (nY2 > yScrn) nY2 = yScrn; nWidth = nX2 - nX; nHeight = nY2 - nY; // 创建一个与屏幕设备描述表兼容的位图 hBitmap = CreateCompatibleBitmap (hScrDC, nWidth, nHeight); // 把新位图选到内存设备描述表中 hOldBitmap = SelectObject(hMemDC, hBitmap); // 把屏幕设备描述表拷贝到内存设备描述表中 BitBlt(hMemDC, 0, 0, nWidth, nHeight, hScrDC, nX, nY, SRCCOPY); //得到屏幕位图的句柄 hBitmap = SelectObject(hMemDC, hOldBitmap); //清除 DeleteDC(hScrDC); DeleteDC(hMemDC); // 返回位图句柄 return hBitmap; } 得到屏幕位图句柄以后,我们 可以把屏幕内容粘贴到剪贴板上. if (OpenClipboard(hWnd)) //hWnd为程序窗口句柄 { //清空剪贴板 EmptyClipboard(); //把屏幕内容粘贴到剪贴板上, \f hBitmap 为刚才的屏幕位图句柄 SetClipboardData(CF_BITMAP, hBitmap); //关闭剪贴板 CloseClipb oard(); } 我们也可以把屏幕内容以位图格式存到磁盘文件上. int SaveBitmapToFile(HBITMAP hBitmap , LPSTR lpFileName) //hBitmap 为刚才的屏幕位图句柄 { //lpFileName 为位图文件名 HDC hDC; //设备描述表 int iBits; //当前显示分辨率下每个像素所占字节数 WORD wBitCount; //位图中每个像素所占字节数 //定义调色板大小, 位图中像素字节大小 , 位图文件大小 , 写入文件字节数 DWORD dwPaletteSize=0, dwBmBitsSize, dwDIBSize, dwWritten; BITMAP Bitmap; //位图属性结构 BITMAPFILEHEADER bmfHdr; //位图文件头结构 BITMAPINFOHEADER bi; //位图信息头结构 LPBITMAPINFOHEADER lpbi; //指向位图信息头结构 HANDLE fh, hDib, hPal,hOldPal=NULL; //定义文件,分配内存句柄,调色板句柄 //计算位图文件每个像素所占字节数 hDC = CreateDC("DISPLAY ib); *lpbi = bi; // 处理调色板 hPal = GetStockObject(DEFAULT_PALETTE); if (hPal) { hDC = GetDC(NULL); hOldPal = SelectPalette(hDC, hPal, FALSE); RealizePalette(hDC); } // 获取该调色板下新的像素值 GetDIBits(hDC, hBitmap, 0, (UINT) Bitmap.bmHeight, (LPSTR)lpbi + sizeof(BITMAPINFOHEADER) +dwPaletteSize, (BITMAPINFOHEADER *) lpbi, DIB_RGB_COLORS); //恢复调色板 if (hOldPal) { SelectPalette(hDC, hOldPal, TRUE); RealizePalette(hDC); ReleaseDC(NULL, hDC); } //创建位图文件 fh = CreateFile(lpFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL FILE_ FLAG_SEQUENTIAL_SCAN, NULL); if (fh == INVALID_HANDLE_VALUE) return FALSE; // 设置位图文件头 bmfHdr.bfType = 0x4D42; // "BM" dwDIBSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + dwPaletteSize + dwBmBitsSize; bmfHdr.bfSize = dwDIBSize; bmfHdr.bfReserved1 = 0; bmfHdr.bfReserved2 = 0; bmfHdr.bfOffBits = (DWORD)sizeof \f (BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER) + dwPaletteSize; // 写入位图文件头 WriteFile(fh, (LPSTR)&bmfHdr, sizeof (BITMAPFILEHEADER), &dwWritten, NULL); // 写入位图文件其余内容 WriteFile(fh, (LPSTR)lpbi, dwDIBSize, &dwWritten, NULL); //清除 GlobalUnlock(hDib); GlobalFree(hDib); CloseHandle(fh); } 16.聊天室服务器端逻辑 一、服务器端所声明的类 class CCSocketDlg : public CDialog { // Construction public: CCSocketDlg(CWnd* pParent = NULL); // standard constructor ~CCSocketDlg(); // Dialog Data //{{AFX_DATA(CCSocketDlg) enum { IDD = IDD_CSOCKET_DIALOG }; CButton m_button; CListCtrl m_list; CEdit m_edit; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CCSocketDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: HICON m_hIcon; // Generated message map functions //{{AFX_MSG(CCSocketDlg) virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); virtual void OnOK(); afx_msg void OnButton1(); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: WSADATA wsaData; SOCKET clisock; SOCKET sListen, sAccept; int addlen; int count,s; int getcount(); void sendtoall(SOCKET,char*); \f struct sockaddr_in ser, cli; //服务器和客户的地址 int iLen; //客户地址长度 int iSend;//发送的数据长度 int flag;//标志位 char buf[1000];//要发送给客户的信息 void CRS(); }; UINT thread(LPVOID); //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CSOCKETDLG_H__2DFDFAF0_3473_43E6_A5CB_DBB8531B370E__INCLUDED_) 二、服务器端 // CSocketDlg.cpp : implementation file //服务器端 #include "stdafx.h" #include "C "CSocket.h" #include "CSocketDlg.h" #include 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 } \f BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCSocketDlg dialog CCSocketDlg::CCSocketDlg(CWnd* pParent /*=NULL*/) : CDialog(CCSocketDlg::IDD, pParent) { //{{AFX_DATA_INIT(CCSocketDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CCSocketDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CCSocketDlg) DDX_Control(pDX, IDC_BUTTON1, m_button); DDX_Control(pDX, IDC_LIST1, m_list); DDX_Control(pDX, IDC_EDIT1, m_edit); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CCSocketDlg, CDialog) //{{AFX_MSG_MAP(CCSocketDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, OnButton1) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCSocketDlg message handlers //初始化对话框 BOOL CCSocketDlg::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); \f 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 int count,s=1; // char buff[100]; CDialog a; CCSocketDlg *dlg=(CCSocketDlg*)AfxGetApp()->GetMainWnd(); count=0; m_list.InsertColumn(0,"消息"); m_list.SetColumnWidth(0,435); m_edit.SetLimitText(99); dlg->sAccept=NULL; //设定地址 dlg->ser.sin _addr.s_addr=htonl(INADDR_ANY); dlg->ser.sin_family=AF_INET; dlg->ser.sin_port=htons(5000); addlen=sizeof(dlg->ser); m_button.EnableWindow(FALSE); //创建服务器端的套接口 dlg->sListen=socket(AF_INET,SOCK_STREAM,0); if (dlg->sListen==INVALID_SOCKET) { m_edit.SetWindowText("创建套接口失败"); return FALSE; } //绑定 if (bind(dlg->sListen,(SOCKADDR*)&(dlg->ser),addlen))=SOCKET_ERROR) { closesocket(dlg->sListen); m_edit.SetWindowText("绑定错误"); return FALSE; } else{ m_edit.SetWindowText("服务器创建成功"); //开始侦听 if (listen(dlg->sListen,5)==SOCKET_ERROR) { m_edit.SetWindowText("侦听失败"); return FALSE; } CRS(); } return TRUE; // return TRUE unless you set the focus to a control \f } void CCSocketDlg::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 CCSocketDlg::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 CCSocketDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CCSocketDlg::OnOK() { // CDialog::OnOK(); } //发送数据 void CCSocketDlg::OnButton1() { char buff[100]; m_edit.GetWindowText(buff,99); m_edit.SetWindowText(""); m_list.InsertItem(count++,buff); //m_list.Scroll(size); if (sAccept!=NULL) //发送 \f send(sAccept,buff,100,0); } CCSocketDlg::~CCSocketDlg() { if (sAccept!=NULL) send(sAccept,"Disconnected InsertItem(dlg->count++,buff); dlg->m_list.InsertItem(dlg->count++,ctime( //发送 send(dlg->sAccept,buff,100,0); //dlg->sendtoall(dlg->sAccept,buff); closesocket(dlg->sAccept); } }//end While closesocket(dlg->sListen); WSACleanup(); } 17.聊天室客户端逻辑 18.克隆对象 class Test { public: Test(int temp) { p1=temp; } Test(Test &c_t)//这里就是自定义的拷贝构造函数 { cout<<"进入copy构造函数"< \f } public: int p1; }; void main() { Test a(99); Test b=a; cout< } //======================================== #include using namespace std; class Internet { public: Internet(char *name,char *address) { cout<<"载入构造函数"< strcpy(Internet::address,address); cname=new char[strlen(name)+1]; if(cname!=NULL) { strcpy(Internet::cname,name); } } Internet(Internet &temp) { cout<<"载入COPY构造函数"< strcpy(Internet::address,temp.address); cname=new char[strlen(name)+1];//这里注意,深拷贝的体现! if(cname!=NULL) { strcpy(Internet::cname,name); } } ~Internet() { cout<<"载入析构函数!"; delete[] cname; cin.get(); } void show(); protected: char name[20]; char address[30]; char *cname; }; void Internet::show() { cout< \f void test(Internet ts) { cout<<"载入test函数"< void main() { Internet a("中国软件开发实验室 tmp.find_first_of(endTag1,offset)-offset,offset); offset=tmp.find_first_of(propTag2,offset)+strlen(%%6)+2; tmp.copy(prop2.begin(),tmp.find_first_of(endTag2,offset)-offset,offset); CString %%8(prop),%%9(prop2); %%10 return 0; } } } else return -1; 20.XML属性文件构造 /* #include using namespace std; */ char sRead[5192]; string description; CFile mFile(_T(%%1),CFile::modeRead); mFile.Read(sRead,5192); int no; if(sRead!=null) { string tmp; while(sRead!=null) { tmp.append(sRead); mFile.Read(sRead,5192); } //%%2="Logs" //%%4="ID" //%%6="Content" //%%3="Log" //%%5="Time" //%%7 code %%8 time %%9 content int offset=tmp.find_last_of("<"+%%3+" "+%%4)+strlen(%%3) +strlen(%%4)+4; tmp.copy(description.begin(),tmp.find_last_of("\\"><"+%%5)- offset,offset); bo=atoi(description.c_str())+1; mFile.Close(); tmp.insert(tmp.find_last_of(""+%%2+">"),"<"+%%3+" "+%%4+"=\\""+itoa(no)+"\\"><"+%%5+">"+%%8+""+%%5+"><"+%%6+">"+%%9+""+%%6+" >"); CFile file(_T(%%1),CFile::modeWrite); file.Write(tmp.c_str()): file.Flush(); file.Close(); \f } else { CFile file(_T(%%1),CFile::modeWrite|CFile::modeCreate); file.Write("<"+%%2+"><"+%%3+" "+%%4+"=\\"0\\"><"+%%5+">"+%%8+""+%%5+"><"+%%6+">"+%%9+""+%%6+">"+%%3 +">"+%%2+">"); file.Flush(); file.Close(); } 21.XML文件节点遍历操作 22.XML文件节点遍历查找 23.多线程端口监听 /* #include #pragma comment(lib,"WS2_32.lib") */ DWORD WINAPI ClientThread(LPVOID lpParam); WORD wVersionRequested; DWORD ret; WSADATA wsaData; BOOL val; SOCKADDR_IN saddr; SOCKADDR_IN scaddr; int err; SOCKET s; SOCKET sc; int caddsize; HANDLE mt; DWORD tid; wVersionRequested = MAKEWORD( 2, 2 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { printf("error!WSAStartup failed!"); return -1; } saddr.sin_family = AF_INET; //截听虽然也可以将地址指定为INADDR_ANY,但是要不能影响正常应用情况下,应该指定具体的IP,留 下127.0.0.1给正常的服务应用,然后利用这个地址进行转发,就可以不影响对方正常应用了 saddr.sin_addr.s_addr = inet_addr(argv[1]); saddr.sin_port = htons(80); if((s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==SOCKET_ERROR) { printf("error!socket failed!"); return -1; } val = TRUE; //SO_REUSEADDR选项就是可以实现端口重绑定的 \f if(setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&val,sizeof(val))!=0) { printf("error!setsockopt failed!"); return -1; } //如果指定了SO_EXCLUSIVEADDRUSE,就不会绑定成功,返回无权限的错误代码; //如果是想通过重利用端口达到隐藏的目的,就可以动态的测试当前已绑定的端口哪个可以成功,就说明具备这个 漏洞,然后动态利用端口使得更隐蔽 //其实UDP端口一样可以这样重绑定利用,这儿主要是以 TELNET服务为例子进行攻击 if(bind(s,(SOCKADDR *)&saddr,sizeof(saddr))==SOCKET_ERROR) { ret=GetLastError(); printf("error!bind failed!"); return -1; } listen(s,2); while(1) { caddsize = sizeof(scaddr); //接受连接请求 sc = accept(s,(struct sockaddr *)&scaddr,&caddsize); if(sc!=INVALID_SOCKET) { mt = CreateThread(NULL,0,ClientThread,(LPVOID)sc,0,&tid); if(mt==NULL) { printf("Thread Creat Failed!"); break; } } CloseHandle(mt); } closesocket(s); WSACleanup(); return 0; 24.多线程端口扫描 /* #include #pragma comment(lib,"WS2_32.lib") */ port_segment port; struct sockaddr_in dest_addr; /* copy the struct to port */ memcpy( &port, arg, sizeof(struct port_segment) ); memset( &dest_addr, 0, sizeof(struct sockaddr_in) ); dest_addr.sin_family = AF_INET; dest_addr.sin_addr.s_addr = port.dest.s_addr; for ( int i = port.min_port; i <= port.max_port; ++i ) { dest_addr.sin_port = htons( i ); /* do the scan with every port */ if ( do_scan(dest_addr) < 0 ) \f continue; } return NULL; } pthread_t *thread; struct in_addr dest_ip[ IP_NUM ]; // IP_NUM ip address if ( argc < 2 ) { fprintf( stderr, "usage: ./scan [ip1] [ip2] .. [ip5]\ " ); exit ( EXIT_FAILURE ); } /* copy all the ip address into dest_ip */ for ( int i = 1; i < argc; ++i ) { if ( inet_aton(argv[i], &dest_ip[i - 1]) == 0 ) { fprintf( stderr, "invalid ip address.\ " ); exit ( EXIT_FAILURE ); } } /* malloc THREAD_NUM thread */ thread = ( pthread_t * )malloc( THREAD_NUM * sizeof(pthread_t) ); for ( int j = 0; j < argc - 1; ++j ) { for ( int i = 0; i < THREAD_NUM; ++i ) { port_segment port; port.dest = dest_ip[ j ]; port.min_port = i * SEG_LEN + 1; /* the last segment */ if ( i == (THREAD_NUM - 1) ) port.max_port = MAX_PORT; else port.max_port = port.min_port + SEG_LEN - 1; /* create threads to scan the ports */ if ( pthread_create(&thread[i], NULL, scan, (void *)&port) != 0 ) my_error( "pthread_create failed" ); /* waiting for the sub threads exit */ pthread_join( thread[i], NULL ); } } /* free the memory */ free( thread ); 25.发送带附件的邮件 /* #include #include #include #pragma comment(lib,"WS2_32.lib") */ const int BASE_MAXLINE = 76; \f const char EOL[] = "\ \ "; const char BASE_TAB[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz01234567+/"; const char HEADER[] = "HELO support.com\ \ " //"AUTH LOGIN\ \ " //+ BASE USER + BASE PASS "MAIL FROM: chinansl@support.com\ \ " "RCPT TO: shadowstar@support.com\ \ " "DATA\ \ " "FROM: chinansl@support.com\ \ " "TO: shadowstar@support.com\ \ " "SUBJECT: this is a test\ \ " "Date: 2002-5-14\ \ " "X-Mailer: shadowstar''''s mailer\ \ " "MIME-Version: 1.0\ \ " "Content-type: multipart/mixed; boundary=\\"#BOUNDARY#\\"\ \ " //"Content-Type: text/plain; charset=gb2312\ \ " "\ \\ ; const char CONTENT[] = "\ \ --#BOUNDARY#\ \ " "Content-Type: text/plain; charset=gb2312\ \ " "Content-Transfer-Encoding: quoted-printable\ \ " "\ \ " "/*************************************************************" " * smtp.cpp - Use SMTP to send an eMail with an Attachment and verify *" " * Copyright (C) 2001-2002 by ShadowStar. *" " * Use and modify freely. *" " * http://shadowstar.126.com/ *" " *************************************************************" " */\ \ " "\ \ "; const char ATT_HEADER[] = "\ \ --#BOUNDARY#\ \ " "Content-Type: application/octet-stream; name=smtp.exe\ \ " "Content-Disposition: attachment; filename=smtp.exe\ \ " "Content-Transfer-Encoding: base\ \ " "\ \ "; //--------------------------------------------------------------------------- int ANSIToBase(const char *szInANSI, int nInLen, char *szOutBase, int nOutLen); WSADATA wsaData; int SockFD; struct sockaddr_in ServAddr; char buf[0x100]; int x; FILE *fp; char *aatt = new char[0x400000]; char *batt = new char[0x555556]; WSAStartup(MAKEWORD(2,2), &wsaData); LPHOSTENT pHost = gethostbyname("172.16.234.111"); SockFD = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); ServAddr.sin_family = AF_INET; ServAddr.sin_addr.s_addr = *(ULONG *)pHost->h_addr_list[0]; ServAddr.sin_port = htons(25); \f connect(SockFD, (struct sockaddr *)&ServAddr, sizeof(ServAddr)); //send HEADER send(SockFD, HEADER, strlen(HEADER), 0); //send CONTENT send(SockFD, CONTENT, strlen(CONTENT), 0); //send ATT_HEADER send(SockFD, ATT_HEADER, strlen(ATT_HEADER), 0); //read attachment fp = fopen(argv[0], "rb"); fseek(fp, 0, 2); x = ftell(fp); if (x > 0x400000) x = 0; rewind(fp); fread(aatt, x, 1, fp); fclose(fp); x = ANSIToBase(aatt, x, batt, 0x555556); //send base attachment send(SockFD, batt, x, 0); send(SockFD, ".\ \ ]; szOutBase[nOutPos++] = BASE_TAB[((c2 << 2) | (c3 >> 6)) & 0x3F]; szOutBase[nOutPos++] = BASE_TAB[c3 & 0x3F]; nLineLen += 4; //Handle the case where we have gone over the max line boundary if (nLineLen > BASE_MAXLINE - 4) { szOutBase[nOutPos++] = EOL[0]; szOutBase[nOutPos++] = EOL[1]; nLineLen = 0; } } // Encode the remaining one or two characters in the input buffer switch (nInLen % 3) { case 0: { szOutBase[nOutPos++] = EOL[0]; szOutBase[nOutPos++] = EOL[1]; break; } case 1: { c1 = szInANSI[nInPos] & 0xFF; szOutBase[nOutPos++] = BASE_TAB[(c1 & 0xFC) >> 2]; szOutBase[nOutPos++] = BASE_TAB[((c1 & 0x03) << 4)]; szOutBase[nOutPos++] = ''''=''''; szOutBase[nOutPos++] = ''''=''''; szOutBase[nOutPos++] = EOL[0]; szOutBase[nOutPos++] = EOL[1]; break; } case 2: { c1 = szInANSI[nInPos++] & 0xFF; c2 = szInANSI[nInPos] & 0xFF; szOutBase[nOutPos++] = BASE_TAB[(c1 & 0xFC) >> 2]; szOutBase[nOutPos++] = BASE_TAB[((c1 & 0x03) << 4) | ((c2 & 0xF0) >> 4)]; szOutBase[nOutPos++] = BASE_TAB[((c2 & 0x0F) << 2)]; szOutBase[nOutPos++] = ''''=''''; szOutBase[nOutPos++] = EOL[0]; szOutBase[nOutPos++] = EOL[1]; break; } default: { return 0; } } szOutBase[nOutPos] = 0; return nOutPos; } 26.接收带附件的邮件 /* \f #include #pragma comment(lib,"WS2_32.lib") */ try{ CComPtr objMail; HRESULT hr; // make sure the DLL is registered hr = objMail.CoCreateInstance(CLSID_Mail); if(SUCCEEDED(hr)) { if(hr== S_OK) { // profile name is compulsory, this is the outlook profile, // i used "outlook express" as configuring it is easier than // "MS outlook" make sure to specify the correct sender's address // for this profile and make sure that outlook express is //the default email client. if(m_strProfile.IsEmpty()) { AfxMessageBox("Please specify email profile name "); return; } if(m_strTo.IsEmpty()) { AfxMessageBox("Please specify recipient's email address "); return; } // by default, it's TestProfile, assumes that a profile with this //name exists in outlook hr= objMail->put_strProfileName((_bstr_t)m_strProfile); hr = objMail->put_strSubject((_bstr_t)m_strSubject); // this is the email or set of email addresses (separated by ,) // which is actually used to send email hr = objMail->put_strEmailAddress((_bstr_t)m_strTo); // recipient is just to show the display name hr = objMail->put_strRecipient((_bstr_t)m_strTo); hr = objMail->put_strAttachmentFilePath((_bstr_t)m_strAttachment); hr = objMail->put_strMessage((_bstr_t)m_strMessage); hr= objMail->Send(); if(hr!=S_OK) AfxMessageBox("Error, make sure the info is correct"); }//if } //if } // try catch(...) { AfxMessageBox("Error, make sure specified info is correct"); \f } 27.Ping /( #include #include #include #pragma comment (lib, "ws2_32.lib" ) #pragma comment (lib, "Iphlpapi.lib") */ DWORD WINAPI PingThread(LPVOID lParam) { int n = (int)(INT_PTR)lParam; IPAddr ip = inet_addr(%%1) + (n << 24); //"192.168.0.0" BYTE mac[8]; ULONG len = sizeof(mac); if (SendARP(ip, 0, (PULONG)mac, &len) == NO_ERROR) { //printf("192.168.0.%d : %02X-%02X-%02X-%02X-%02X-%02X\ General Public License as published by the Free Software Foundation. csproxyv1.3 */ /* #include #include #include "server.h" #define PORT 8080 */ start_server(PORT); 30.创建启动线程 UINT Listen(LPVOID pParam) { return 0; } CWinThread *pThread=AfxBeginThread(Listen,&port); \f 31.线程挂起唤醒 ::SuspendThread(pThread->m_hThread);// //pThread->SuspendThread(); //工作者线程时,用于子挂起,此时的线程类应该是个全局的对象; ::ResumeThread(pThread->m_hThread);//API函数的唤醒线程 //pThread->ResumeThread(); 32.线程插入终止 DWORD dwExitCode; GetExitCodeThread(pThread->m_hThread, &dwExitCode ); AfxEndThread( dwExitCode, TRUE ); 33.HTTP多线程下载 // CInternetSession在遇到一些错误时会抛出异常,因此必须包起来 TRY { CInternetSession sess ; // 统一以二进制方式下载 DWORD dwFlag = INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_RELOAD ; CHttpFile * pF = (CHttpFile*)sess.OpenURL(strFilename, 1, dwFlag); ASSERT(pF); if (!pF) {AfxThrowInternetException(1);} // 得到文件大小 CString str ; pF->QueryInfo (HTTP_QUERY_CONTENT_LENGTH, str) ; int nFileSize = _ttoi(str) ; char * p = new[nFileSize] ; while (true) { // 每次下载8Kb int n = pF->Read (p, (nFileSize < 8192) ? nFileSize : 8192) ; if (n <= 0) break ; p += n ; nFileSize -= n ; } delete[] p ; delete pF ; } CATCH_ALL(e) {} END_CATCH_ALL int n = pF->GetLength() ; while (n) { int * p = new BYTE[n] ; pF->Read (p, n) ; delete[] p ; n = pF->GetLength() ; } if (n == 0) { DWORD dw ; if (::InternetQueryDataAvailable ((HINTERNET)(*pF), &dw, 0, 0) && (dw == 0)) { \f // 到这里就代表文件下载成功了 } } 34.MP3播放 MCI_OPEN_PARMS openpa; openpa.lpstrDeviceType="MCI_DEVTYPE_WAVEFORM_AUDIO"; openpa.lpstrElementName=%%1; mciSendCommand(NULL,MCI_OPEN,MCI_DEVTYPE_WAVEFORM_AUDIO,(DWORD)(LPVOID)&openpa); m_wDeviceID=openpa.wDeviceID; m_open=true; MCI_OPEN_PARMS playpa; // playpa.dwCallback=(DWORD)pWnd->m_hWnd; mciSendCommand(m_wDeviceID,MCI_SEEK,MCI_SEEK_TO_START,NULL); mciSendCommand(m_wDeviceID,MCI_PLAY,NULL,(DWORD)(LPVOID)&playpa); // return false;*/ mciSendCommand(m_wDeviceID,MCI_STOP,NULL,NULL); m_open=false; if(m_wDeviceID) { mciSendCommand(m_wDeviceID,MCI_STOP,MCI_WAIT,NULL); mciSendCommand(m_wDeviceID,MCI_CLOSE,NULL,NULL); } m_wDeviceID=0; 35.WAV播放 MCI_OPEN_PARMS openpa; openpa.lpstrDeviceType="MCI_DEVTYPE_WAVEFORM_AUDIO"; openpa.lpstrElementName=%%1; mciSendCommand(NULL,MCI_OPEN,MCI_DEVTYPE_WAVEFORM_AUDIO,(DWORD)(LPVOID)&openpa); m_wDeviceID=openpa.wDeviceID; m_open=true; MCI_OPEN_PARMS playpa; // playpa.dwCallback=(DWORD)pWnd->m_hWnd; mciSendCommand(m_wDeviceID,MCI_SEEK,MCI_SEEK_TO_START,NULL); mciSendCommand(m_wDeviceID,MCI_PLAY,NULL,(DWORD)(LPVOID)&playpa); // return false;*/ mciSen dCommand(m_wDeviceID,MCI_STOP,NULL,NULL); m_open=false; if(m_wDeviceID) { mciSendCommand(m_wDeviceID,MCI_STOP,MCI_WAIT,NULL); mciSendCommand(m_wDeviceID,MCI_CLOSE,NULL,NULL); } m_wDeviceID=0; \f
