Write simple remote control by yourself (C Edition)

Source: Internet
Author: User
Tags htons

First, let's talk about the communication process between the two parties: the server listens after it starts, and the client actively connects to the server. After the connection is successful, a thread is established for it to receive and process control commands.

The following describes the implementation of the client.
The functions of the client are actually very simple. After you connect to the server, you do not need to do anything. When you click the "send control" button, you can create different commands based on the control options for sending.
Below is the connection to the serverCode:

// Obtain the Server IP Address
Byte values, CH2, CH3, and methane;
M_edtserver.getaddress (Shard, CH2, CH3, and methane );
M_strserver.format ("% u. % u", examples, CH2, CH3, and methane );

Wsadata ws;
Int ret;
Struct sockaddr_in server;

If (wsastartup (makeword (2, 2), & ws )! = 0)
{
Return;
}
If (sclient = socket (af_inet, sock_stream, 0) = invalid_socket)
{
Return;
}

Server. Sin_family = af_inet;
Server. sin_port = htons (m_nport );
Server. sin_addr.s_addr = inet_addr (m_strserver );

If (connect (sclient, (struct sockaddr *) & server, sizeof (server) = 0)
{
M_edtstatus.setwindowtext ("TCP port connected: 12345 ");
}

 

The following is the response function of the send control button.ProgramThere are only three basic functions: send information (enable the recipient to pop up a dialog box to display the information you sent in the past) system control (including shutdown, restart, screen capture, pop-up/shutdown of the optical drive), mouse control (including random movement, disable input, switch between left and right keys ). I used three single counters to determine the basic type of controls. The drop-down box is used to select sub-functions. Therefore, two controls are sent for each control. The basic functions are determined for the first time, and the sub-functions are determined for the second time.

Char cmdbuffer [1024];
Char struct type [5];
Cstring strbuffer;
Int iselect;
Handle hthread;
DWORD dwthread;

// constructor
If (m_rdomsg.getcheck () = 1)
{// send a message
m_edtmsg.getwindowtext (strbuffer ); // obtain the content in the input box
sprintf (cmdbuffer, "% s", strbuffer);
sprintf (partition type, "% C",'s ');
}< br> else if (m_rdoctrl.getcheck () = 1)
{// System Control
// only the option index number returned by the drop-down box is sent, the server directly determines sub-function commands Based on the index
iselect = m_cmbctrl.getcursel ();
sprintf (cmdbuffer, "% d", iselect);
sprintf (partition type, "% C", 'C');
}< br> else if (m_rdomouse.getcheck () = 1)
{// mouse control
iselect = m_cmbmouse.getcursel ();
sprintf (cmdbuffer, "% d", iselect);
sprintf (mouse type, "% C", 'M');
}< br> else
{< br> return;
}

// First, send the basic command type
Int ret = Send (sclient, struct type, strlen (partition type) + );
If (ret = socket_error) | (ret = 0 ))
{
Return;
}
// Sending sub-function number
Ret = Send (sclient, cmdbuffer, strlen (cmdbuffer) + 1, 0 );
If (ret = socket_error) | (ret = 0 ))
{
Return;
}
Return;

Next, I will post a piece of screen image on the server to display it in the picture control. Due to the tight schedule, I was so lazy If I Didn't transmit the image together, after the server intercepts the screen, it directly stores it in the C root directory, and the control terminal reads it directly to this location. Haha, I specifically told the teacher that the teacher gave me a try considering the time limit, it actually uses some encoding.AlgorithmCompress the image, for example, JPEG.

Hbitmap = (hbitmap) LoadImage (AfxGetInstanceHandle (), "C: \ test.bmp ",
Image_bitmap, 0, 0, lr_createdibsection | lr_loadfromfile );

CDC * PDC = getdlgitem (idc_file_static)-> getdc ();
CDC screen;
Screen. createcompatibledc (PDC );
Crect rect;
Getclientrect (rect );
Hbitmap oldbitmap = (hbitmap) screen. SelectObject (hbitmap );
PDC-> bitblt (, rect. Width (), rect. Height (), & screen, srccopy );
Return;

Next, let's look at the server, the old rule. First, let's look at the listening function.

Wsadata ws;
Int iaddrsize;
Handle hthread;
DWORD dwthread;
Struct sockaddr_in local, client;

If (wsastartup (makeword (2, 2), & ws )! = 0)
{
Return;
}

If (slisten = socket (af_inet, sock_stream, 0) = invalid_socket)
{
Return;
}

Local. sin_family = af_inet;
Local. sin_port = htons (12345 );
Local. sin_addr.s_un.s_addr = inaddr_any;

If (BIND (slisten, (struct sockaddr *) & Local, sizeof (struct sockaddr) = socket_error)
{
Closesocket (slisten );
Return;
}

Listen (slisten, 5 );

Iaddrsize = sizeof (Client);
Sclient = accept (slisten, (struct sockaddr *) & client, & iaddrsize );
If (sclient = invalid_socket)
{
Closesocket (slisten );
Return;
}

// Create a session thread
Hthread = createthread (null, 0, clientthread, (lpvoid) sclient, 0, & dwthread );
If (hthread = NULL)
{
Return;
}
Closehandle (hthread );

Closesocket (slisten );
Wsacleanup ();
Return;

Let's look at the code of the thread function.
Socket sock = (socket) Param;
Char szbuff [max_path];
Int ret;

While (1)
{
Ret = Recv (sock, szbuff, sizeof (szbuff), 0 );
If (ret = 0)
Break;
Else if (ret = socket_error)
Break;
Else
Szbuff [RET] = '\ 0 ';

Switch (szbuff [0])
{
Case's ': // display the message
Ret = Recv (sock, szbuff, sizeof (szbuff), 0 );
Szbuff [RET] = '\ 0 ';
Showmessage (szbuff );
Break;
Case 'C': // System Control
Ret = Recv (sock, szbuff, sizeof (szbuff), 0 );
Szbuff [RET] = '\ 0 ';
Ret = atoi (szbuff );
Systemcontrol (RET );
Break;
Case 'M': // mouse control
Ret = Recv (sock, szbuff, sizeof (szbuff), 0 );
Szbuff [RET] = '\ 0 ';
Ret = atoi (szbuff );
Mousecontrol (RET );
Break;
Default:
Break;
}
}
Return 0;

The next step is to paste all the three processing functions. Note that these functions must be defined as global functions, rather than class member functions. In this case, they cannot be accessed in the thread functions.

Void showmessage (lpctstr MSG)
{: MessageBox (null, MSG, "info", mb_ OK );
}
Void systemcontrol (INT select)
{
Switch (select)
{
Case 0:
Opencdoor (); // enable the optical drive
Break;
Case 1:
Closecdoor (); // disable the optical drive
Break;
Case 2:
Snapscreen (); // capture the screen
Break;
Case 3:
Preprocess (); // escalate process Permissions
Rebootsystem (); // restart the system
Break;
Case 4:
Preprocess ();
Shutdown (); // shut down the system
Break;
Default:
Break;
}
}
Void mousecontrol (INT select)
{
Int I = 0;
Int Nx = 0;
Int ny = 0;

Switch (select)
{
Case 0:
// Move the mouse randomly within 25 seconds
For (I = 0; I <= 49; I ++)
{
Nx = rand () %1024;
NY = rand () % 768;
: Setcursorpos (NX, NY );
Sleep (500 );
}
Break;
Case 1:
// Lock the mouse and keyboard response within 10 seconds
Blockinput (true );
Sleep (10000 );
Blockinput (false );
Break;
Case 2:
// Switch the mouse's left and right keys within 10 seconds'
Swapmousebutton (true );
Sleep (10000 );
Swapmousebutton (false );
Break;
Default:
Break;
}
}
Finally, I will post the detailed process of some functions.
// Capture the screen. The code is from the Hacker defense line.
Bool snapscreen ()
{
Cdc dc;
Int nwidth;
Int nheight;

DC. createdc ("display", null );

Nwidth = getdevicecaps (DC, horzres );
Nheight = getdevicecaps (DC, vertres );

CDC dcmem;
Dcmem. createcompatibledc (& DC );

Cbitmap bitmap;
Bitmap. createcompatiblebitmap (& DC, nwidth, nheight );

Cbitmap * poldbitmap = dcmem. SelectObject (& Bitmap );
Dcmem. bitblt (0, 0, nwidth, nheight, & DC, 0, srccopy );
Dcmem. SelectObject (poldbitmap );

Cstring strfile = "C: \ test.bmp ";
Savebitmaptofile (DC. getsafehdc (), bitmap, strfile );
DC. deletedc ();

Return true;
}
// The savebitmaptofile function saves the captured image and asks the BMP file
Bool savebitmaptofile (HDC, cbitmap & bitmap, lpctstr lpszfilename)
{
Bool ret = true;
Bitmap BTM;
Bitmap. getbitmap (& BTM );
DWORD size = BTM. bmwidthbytes * BTM. bmheight;

Hglobal hmem = globalalloc (gmem_fixed | gmem_zeroinit, size );
If (hmem = NULL)
Return false;

Lpstr lpdata = (lpstr) globallock (hmem );

Bitmapinfoheader BiH;
BiH. bisize = sizeof (bitmapinfoheader );
BiH. biwidth = BTM. bmwidth;
BiH. biheight = BTM. bmheight;
BiH. biplanes = 1;
BiH. bibitcount = BTM. bmbitspixel;
BiH. bicompression = 0;
BiH. bisizeimage = size;
BiH. bixpelspermeter = 0;
BiH. biypelspermeter = 0;
BiH. biclrused = 0;
BiH. biclrimportant = 0;

If (getdibits (HDC, bitmap, 0, BiH. biheight, lpdata, (bitmapinfo *)
& BiH, dib_rgb_colors) = 0)
{
Globalfree (hmem );
Return false;
}

Bitmapfileheader BFH;
BFH. bftype = (Word) ('M' <8) | 'B ');
BFH. bfreserved1 = 0;
BFH. bfreserved2 = 0;
BFH. bfsize = sizeof (BFH) + size;
BFH. bfoffbits = sizeof (BFH );

Cfile BF;
If (BF. Open (lpszfilename, cfile: modecreate | cfile: modewrite ))
{
BF. writehuge (& BFH, sizeof (bitmapfileheader ));
BF. writehuge (& BiH, sizeof (bitmapinfoheader ));
BF. writehuge (lpdata, size );
BF. Close ();
}
Else
Ret = false;
Globalfree (hmem );
Return ret;
}
// Code for elevation of process Permissions
Bool preprocess ()
{
Handle htoken;
Token_privileges tkp;
If (openprocesstoken (getcurrentprocess (),
Token_adjust_privileges | token_query, & htoken) = 0)
Return false;
If (lookupprivilegevalue (null, se_shutdown_name, & tkp. Privileges [0]. luid) = 0)
Return false;

Tkp. privilegecount = 1;
Tkp. Privileges [0]. Attributes = se_privilege_enabled;
If (adjusttokenprivileges (htoken, false, & tkp, 0, (ptoken_privileges) null, 0) = 0)
Return false;
Return true;
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.