我是 C 的新手(实际上是所有编译语言),下面你会看到我的可怕代码,我尝试接收命令,后来我希望执行它(尚未实现)。
我在 _popen 函数上获取了 Microsoft 的示例代码并对其进行了修改(非常轻微),但由于某种原因,它在收到命令后使我的程序崩溃。如果我将此代码块移到命令接收器部分上方,它就可以正常工作。我是在覆盖另一个内存地址还是什么?
如果您需要服务器(用 python 编写),请告诉我。希望你能帮助有需要的菜鸟。
#include <winsock2.h>
#include <stdio.h>
#include <windows.h>
int sendall(int sock, char *message, unsigned int size);
int connect(char address[], short port);
char* recvall(int sock, unsigned int *msgsize);
int main(){
char address[] = "127.0.0.1";
short port = 1234;
int wait = 5000;
//Connect back
int sock = 1;
printf("Connecting...\n");
sock = connect(address, port);
while(sock == 1){
WSACleanup();
Sleep(wait);
sock = connect(address, port);
}
printf("Succesfully conneted\n");
char test[] = "ABCDEFGH";
sendall(sock,test, 8);
unsigned int msgsize;
char *msg = recvall(sock,&msgsize);
printf("%s\n", msg);
printf("%d\n", msgsize);
//RUN COMMAND
char psBuffer[128];
FILE *pPipe;
printf("There\n");
if( (pPipe = _popen( "ipconfig", "rt" )) == NULL )
exit( 1 );
printf("Out\n");
while(fgets(psBuffer, 128, pPipe)){
printf(psBuffer);
}
if (feof( pPipe)){
printf( "\nProcess returned %d\n", _pclose( pPipe ) );
}else{
printf( "Error: Failed to read the pipe to the end.\n");
}
//RUN COMMAND END
Sleep(10000);
return 0;
}
int sendall(int sock, char *message, unsigned int size){
//Send size packet
char sizepacket[12];
sprintf (sizepacket, "%012u",size);
send(sock, sizepacket, 12, 0);
//Send data
unsigned int left = size;
unsigned int offset = 0;
while(left>0){
if(left<1024){
send(sock, (message+offset), left, 0);
left = 0;
}else{
send(sock, (message+offset), 1024, 0);
offset = offset + 1024;
left = left - 1024;
}
}
return 0;
}
char* recvall(int sock, unsigned int *size){
char *message;
//Get size packet
char sizebuff[24];
memset (&sizebuff,0,24);
recv(sock, sizebuff, 12, 0);
*size = atoi(sizebuff);
//Alloc space for message
message = (char*) malloc(*size + 1);
memset(message,0,1024);
//Get data
unsigned int left = *size;
unsigned int offset = 0;
while(left>0){
if(left<1024){
recv(sock, (message+offset), left, 0);
left = 0;
}else{
recv(sock, (message+offset), 1024, 0);
offset = offset + 1024;
left = left - 1024;
}
}
return message;
}
int connect(char address[], short port){
int returnvalue;
WSADATA wsaData;
returnvalue = WSAStartup(MAKEWORD(2,2), &wsaData);
if(returnvalue != 0){
return 1;
}
int sock;
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sock == 0){
return 1;
}
//Create struct
struct sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr(address);
clientService.sin_port = htons(port);
returnvalue = connect(sock, (SOCKADDR*) &clientService, sizeof(clientService));
if (returnvalue != 0){
closesocket(sock);
WSACleanup();
return 1;
}
return sock;
}