C language socket-analog remote cmd (the client sends a command to the server, the server executes the command)

Source: Internet
Author: User
Tags htons

Service-side (server)
#include <stdio.h>#include<winsock2.h>#pragmaComment (lib, "Ws2_32.lib")//Add the Ws2_32.lib to the link library on the links page#definePORT 15001//Port of communication (referred to as server side)#defineERROR 0#defineBuffer_size 1024//Note: This server-side data receive buffer >= the client-side data send buffer, which otherwise causes a buffer overflow/*Service-side principle: 1, the server process to create socket 2, bind the local address to the created socket, to ternary group {< Communication Protocol >,<IP address >,< port number;} identify the socket on the network 3, the socket into the listening mode, and ready to accept the connection request 4, accept the request, you can receive the data sent by the client and run as a local DOS command*/intMain () {wsadata wsadata; if(WSAStartup (Makeword (2,0), &wsadata) ==socket_error)//starts the Winsock, WSAStartup () function initializes the Winsock DLL{printf ("Socket Initialize fail!\n"); Exit (1);                                        } SOCKET sock; //The service process creates a socket handle (for listening)    if(Sock=socket (Af_inet,sock_stream,0)) ==error)//Call the socket () function to create a stream socket, parameters (network address type, socket type, network protocol){printf ("Socket create!\n");          WSACleanup (); Exit (1); }      structSockaddr_in serveraddr;//the SOCKADDR_IN structure is used to identify the address under the TCP/IP protocol and can be cast to the SOCKADDR structureServeraddr.sin_family=af_inet;//the sin_family field must be set to Af_inet, which indicates that the socket is in the Internet domainServeraddr.sin_port=htons (port);//The Sin_port field is used to specify the service port, to avoid conflictsServeraddr.sin_addr.s_addr=inaddr_any;//The sin_addr field is used to save an IP address as a 4-byte number, an unsigned long integer, or a local or remote IP address depending on the usage    if(Bind (sock, (LPSOCKADDR) &serveraddr,sizeof(SERVERADDR)) ==socket_error)//call the bind () function to bind the local address to the socket you created to identify the socket on the network{printf ("Bind fail!\n");          Closesocket (sock);          WSACleanup (); Exit (1); } printf ("Server Socket port:%d\n", Ntohs (Serveraddr.sin_port)); if(Listen (sock,Ten) ==socket_error)//Call the Listen () function to place the socket in listening mode and prepare to accept the connection request, parameter (the bundle of disconnected socket descriptors, waiting for the maximum queue length of the connection){printf ("Listen fail!\n");          Closesocket (sock);          WSACleanup (); Exit (1);            } SOCKET Msgsock; //creates a new socket (used to receive the return value of the Accept function, which represents the connection of the client that has been accepted, and thus receives the data from client)    CharBuf[buffer_size];//data Receive buffers     while(1)      {          if(Msgsock=accept (sock, (LPSOCKADDR)0,(int*)0)) ==invalid_socket)//after entering the listening state, call the Accept () function to receive the client's connection request and pass the connection to the Msgsock socket, and the original sock socket continues to listen for other client connection requests{printf ("Accept fail!\n"); Continue; } memset (BUF,0,sizeof(BUF));//initializing the data receive bufferRecv (Msgsock,buf,buffer_size,0);//receiving the data sent by the client .        if(buf[0]=='e'&& buf[1]=='x'&& buf[2]=='I'&& buf[3]=='T')//"Exit" command, exit the program{printf ("The end.\n");  Break; } printf ("c:\\socket\\server>%s", BUF);                        System (BUF); //local Run the command from the client: This is too much, if you pass a format command, the server may be destroyedclosesocket (Msgsock); } closesocket (sock); //Close SocketWSACleanup ();//terminating the use of the Winsock DLLs and freeing the resources    return 0;} 

clients (client)
#include <winsock2.h>#include<stdio.h>#pragmaComment (lib, "Ws2_32.lib")//Add the Ws2_32.lib to the link library on the links page//#define IP "172.18.68.243"//test on both computers, IP is the server-side IP address#defineIP "127.0.0.1"//test on a single computer, IP is a local loopback address#definePORT 15001//Note: The client sets the port of communication = port on the server side#defineBuffer_size 1024//data Send buffer size/*Client principle: 1, the client process to create socket 2, the client sends a connection request to the server process 3, when the server accepts the request, the client can send data to the server*/intMain () {CharBuf[buffer_size];//BUF array holds messages sent by the client    intInputlen;//used to enter a character Shizhan variable     while(1) {printf ("c:\\socket\\client>"); Inputlen=0; memset (BUF,0,sizeof(BUF));  while((Buf[inputlen++]=getchar ())! ='\ n')//Enter with enter key for end identification        {            ; }        if(buf[0]=='e'&& buf[1]=='x'&& buf[2]=='I'&& buf[3]=='T') {printf ("The end.\n");  Break;          } wsadata Wsadata; if(WSAStartup (Makeword (2,0), &wsadata) ==socket_error)//the WSAStartup () function initializes a Winsock DLL{printf ("Socket Initialize fail!\n"); Continue;                                            } SOCKET sock; //client process creates sockets        if(Sock=socket (Af_inet,sock_stream,0)) ==socket_error)//Create a flow socket (consistent with the service side){printf ("Socket Create fail!\n");              WSACleanup (); Continue; }          structSockaddr_in clientaddr;//the SOCKADDR_IN structure is used to identify the address under the TCP/IP protocol and can be cast to the SOCKADDR structureClientaddr.sin_family=af_inet;//refers to the Internet domainClientaddr.sin_port=htons (port);//Specify the ports reserved by the serverCLIENTADDR.SIN_ADDR.S_ADDR=INET_ADDR (IP);//Specifies the IP address that the server is bound to        if(Connect (sock, (LPSOCKADDR) &clientaddr,sizeof(CLIENTADDR)) ==socket_error)//call the Connect () function to make a connection request to the server process{printf ("Connect fail!\n");              Closesocket (sock);              WSACleanup (); Continue; } Send (Sock,buf,buffer_size,0);//sending data to the serverClosesocket (sock);//Close SocketWSACleanup ();//terminates the use of the Winsock DLL and frees the resource for the next use    }      return 0;} 

Reference: https://blog.csdn.net/lynch0571

C language socket-analog remote cmd (the client sends a command to the server, the server executes the command)

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.