基於visual c++之windows核心編程程式碼分析(49)基於匿名管道實現遠端控制

來源:互聯網
上載者:User

 匿名管道是一種未命名的、單向管道,通常用來在一個父進程和一個子進程之間傳輸資料。匿名的管道只能實現本地機器上兩個進程間的通訊,而不能實現跨網路的通訊。

匿名管道
     匿名管道是一種未命名的、單向管道。通常用來在父進程和子進程之間傳輸資料。匿名管道總是本地的,不能在網路之間傳遞資料。
匿名管道操作
    CreatePipe函數建立一個匿名管道,並且返回兩個控制代碼:一個讀管道的控制代碼和一個寫管道的控制代碼。讀控制代碼具有管道的唯讀許可權,寫控制代碼具有管道的唯寫權 限。為了利用管道交換資料,管道服務端必須把管道控制代碼傳給另一個進程。通常情況下,這是通過繼承實現的(參見1.1.2);就是說,父進程允許子進程繼承 這個控制代碼。進程也可以使用DuplicateHandle函數複製一個管道控制代碼,再通過一些處理序間通訊機制,比如DDE或者共用記憶體,把它發送給另一個不 相關的進程。
     管道服務端可以給管道服務端發送讀控制代碼或者寫控制代碼,這取決於用戶端要用這個管道發送資料還是擷取資料。要從管道讀取資料,以管道的讀控制代碼為參數調用 ReadFile函數。當另一個進程向管道寫入資料是,ReadFile函數返回。如果管道的所有寫控制代碼被關閉,或者讀取資料時有錯誤發 生,ReadFile函數也會返回。
     要向管道寫入資料,以管道的寫控制代碼問參數,調用WriteFile函數。資料被完全寫入管道,或者出錯,WriteFile將會返回。如果管道的緩衝已 滿,且還有尚未寫完的資料,直到另一個進程從管道讀取資料前,WriteFile函數都不會返回。緩衝的大小是在管道服務端調用CreatePipe函數 時指定的。
     匿名管道不支援非同步讀寫。這意味著不能使用ReadFileEx和WriteFileEx函數讀寫匿名管道。另外,使用匿名管道時,ReadFile和WriteFile函數的lpOverlapped參數也會被忽略。
     匿名管道會一直存在,直到所有的讀寫控制代碼全部被關閉。進程可以調用CloseHandle函數關閉管道控制代碼。進程終止時,所有的管道控制代碼也會被自動關閉。
 
雙匿名管道實現通訊

#include <windows.h>#include <stdio.h>//雙匿名管道實現寫入讀取int cmd_shell(SOCKET target){STARTUPINFO g_stStartUp;PROCESS_INFORMATION g_stProcInfo;HANDLE reHandle1,wrHandle1;HANDLE reHandle2,wrHandle2;char enter_key[2] = {0x0d,0x0a};//填充SECURITY_ATTRIBUTES結構SECURITY_ATTRIBUTES stSecurity;stSecurity.nLength = sizeof(SECURITY_ATTRIBUTES);stSecurity.lpSecurityDescriptor = NULL;stSecurity.bInheritHandle = TRUE;//繼承性//建立兩個管道CreatePipe(&reHandle1,&wrHandle1,&stSecurity,0);CreatePipe(&reHandle2,&wrHandle2,&stSecurity,0);//建立進程前填充STARTUPINFO結構GetStartupInfo(&g_stStartUp);g_stStartUp.hStdInput = reHandle1;g_stStartUp.hStdOutput = wrHandle2;g_stStartUp.hStdError = wrHandle2;g_stStartUp.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;g_stStartUp.wShowWindow = SW_HIDE;//建立進程CreateProcess啟動這個控制台應用程式、if(CreateProcess(NULL,"cmd.exe",NULL,NULL,TRUE,NORMAL_PRIORITY_CLASS,NULL,NULL,&g_stStartUp,&g_stProcInfo)){DWORD bytes_read,bytes_write,ret;char buf[512] = {0};while(1){memset(buf,'\0',512);PeekNamedPipe(reHandle2,buf,512,&bytes_read,NULL,NULL);if(bytes_read != 0){ret = ReadFile(reHandle2,buf,bytes_read,&bytes_read,NULL);send(target,buf,strlen(buf),0);if(ret<=0){fprintf(stderr,"error on pipe %d",GetLastError());break;}}else{bytes_read = recv(target,buf,512,0);printf("%s",buf);if(bytes_read<=0){fprintf(stderr,"error %d",GetLastError());}WriteFile(wrHandle1,buf,strlen(buf),&bytes_write,NULL);WriteFile(wrHandle1,enter_key,2,&bytes_write,NULL);if(strcmp(buf,"exit") == 0){send(target,"串連關閉",8,0);break;}}}Sleep(10);}printf("now Closing\n");CloseHandle(g_stProcInfo.hProcess);CloseHandle(g_stProcInfo.hThread);printf("now closing Pipe\n");return 0;}

遠端控制用戶端加入匿名管道通訊

#include "stdafx.h"#include "用戶端.h"#include "用戶端Dlg.h"#include <winsock.h>#pragma comment(lib,"ws2_32")DWORD WINAPI ServerThread(LPVOID lparam);DWORD WINAPI GoThread(LPVOID lparam);#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endifSOCKET server,client;SOCKADDR_IN serveraddr;char szGo[64];/////////////////////////////////////////////////////////////////////////////// CAboutDlg dialog used for App Aboutclass 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// Implementationprotected://{{AFX_MSG(CAboutDlg)//}}AFX_MSGDECLARE_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_MAPEND_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CMyDlg dialogCMyDlg::CMyDlg(CWnd* pParent /*=NULL*/): CDialog(CMyDlg::IDD, pParent){//{{AFX_DATA_INIT(CMyDlg)m_ipaddr = _T("");m_port = 0;//}}AFX_DATA_INIT// Note that LoadIcon does not require a subsequent DestroyIcon in Win32m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);}void CMyDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CMyDlg)DDX_Text(pDX, IDC_IPADDR, m_ipaddr);DDX_Text(pDX, IDC_PORT, m_port);//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CMyDlg, CDialog)//{{AFX_MSG_MAP(CMyDlg)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED(IDC_CONNECT, OnConnect)ON_BN_CLICKED(IDC_GO, OnGo)ON_BN_CLICKED(IDC_CLEAR, OnClear)//}}AFX_MSG_MAPEND_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CMyDlg message handlersBOOL CMyDlg::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 dialogSetIcon(m_hIcon, TRUE);// Set big iconSetIcon(m_hIcon, FALSE);// Set small icon//初始化庫SetDlgItemText(IDC_IPADDR,"127.0.0.1");SetDlgItemText(IDC_PORT,"1234");UpdateData(true);WSADATA wsadata;WORD word = MAKEWORD(2,2);WSAStartup(word,&wsadata);return TRUE;  // return TRUE  unless you set the focus to a control}void CMyDlg::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 CMyDlg::OnPaint() {if (IsIconic()){CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);// Center icon in client rectangleint 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 icondc.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 CMyDlg::OnQueryDragIcon(){return (HCURSOR) m_hIcon;}void CMyDlg::OnConnect() {UpdateData(true);CreateThread(NULL,NULL,ServerThread,this,NULL,NULL);}DWORD WINAPI ServerThread(LPVOID lparam){CMyDlg *pDlg = (CMyDlg *)lparam;server = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);serveraddr.sin_family = AF_INET;serveraddr.sin_port = htons(pDlg->m_port);serveraddr.sin_addr.S_un.S_addr = inet_addr(pDlg->m_ipaddr);client = connect(server,(SOCKADDR *)&serveraddr,sizeof(serveraddr));if(client == SOCKET_ERROR){MessageBox(NULL,"SORRY","串連出錯",MB_OK);return -1;}MessageBox(NULL,"CONGRATULATE!","串連成功",MB_OK);pDlg->SetDlgItemText(IDC_INFO,"串連成功");char szRecv[1024];CString str0,str1;memset(szRecv,0,1024);while(1){recv(server,szRecv,1024,0);pDlg->GetDlgItemText(IDC_READ,str1);str0 = szRecv;str0 += "\r\n";str0 += str1;pDlg->SetDlgItemText(IDC_READ,str0);}return 0;}void CMyDlg::OnGo() {memset(szGo,0,64);GetDlgItem(IDC_WRITE)->GetWindowTextA(szGo,64);CreateThread(NULL,0,GoThread,this,NULL,NULL);}DWORD WINAPI GoThread(LPVOID lparam){CMyDlg *pDlg = (CMyDlg *)lparam;char enter_key[2] = {0x0d,0x0a};send(server,szGo,sizeof(szGo),0);if(strcmp(szGo,"exit") == 0){Sleep(100);pDlg->SetDlgItemText(IDC_INFO,"未串連");closesocket(server);closesocket(client);WSACleanup();exit(0);}return 0;}void CMyDlg::OnClear() {SetDlgItemText(IDC_READ,"");}

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.