コマンドを実行する単純なサーバープログラムを作成し、その結果をクライアントに送信します。 popen()
、pipe()
、dup2()
、fork()
などを含む無数の例を読んだが、それらのどれも私のために働いていなかったし、コードをうまく説明しなかった。私も自分でやろうとしましたが、成功しませんでした。十分に文書化された例を私に提供してもらえますか?ここで サーバー上でコマンドを実行し、結果をWindowsのクライアントに送信します
void server_receive() {
struct sockaddr_in from;
int from_len, recv_len;
char buf[BUFLEN], path[256]; // BUFLEN = 1024
// Getting the path for the command to execute
strcpy(path, getenv("SYSTEMDRIVE"));
strcat(path, "\\WINDOWS\\System32\\tasklist.exe");
from_len = sizeof(from);
memset(buf, '\0', BUFLEN);
// Receiving the command
// I'll add some if-else statements to handle various commands, but for
// now I just need to see if I can even get one to work.
if((recv_len = recvfrom(sockt, buf, BUFLEN, 0, (struct sockaddr*) &from, &from_len)) == SOCKET_ERROR) {
printf("[ERROR] recvfrom() failed: %d.\n\n", WSAGetLastError());
} else {
printf("Packet received from %s:%d\n", inet_ntoa(from.sin_addr), ntohs(from.sin_port));
printf("Data: %s\n\n", buf);
// Code to execute tasklist (I used _popen())
// and send everything back to the client (I used TransmitFile())
}
}
をそしてここで、サーバーにコマンド/メッセージを送信するコードです:言うまでもなく
void client_send(char server[], unsigned short port) {
struct sockaddr_in to;
int s, to_len = sizeof(to);
char buf[BUFLEN]; // BUFLEN = 1024
char message[BUFLEN];
memset((char*) &to, 0, sizeof(to));
to.sin_family = AF_INET;
to.sin_port = htons(port);
to.sin_addr.S_un.S_addr = inet_addr(server);
while(true) {
printf("Enter message: ");
gets(message);
if (sendto(sockt, message, strlen(message), 0, (struct sockaddr*) &to, to_len) == SOCKET_ERROR) {
printf("[ERROR] sendto() failed: %d.\n\n" , WSAGetLastError());
}
memset(buf, '\0', BUFLEN);
if (recvfrom(sockt, buf, BUFLEN, 0, (struct sockaddr*) &to, &to_len) == SOCKET_ERROR) {
printf("[ERROR] recvfrom() failed: %d.\n\n", WSAGetLastError());
} else {
printf("Server's response: %s\n\n", buf); /* The result of tasklist
should be outputted by this line of code, however I'm concerned about the
relatively small receive length (BUFLEN = 1024).*/
}
}
}
、これら二つの機能私のコードの一部です。あなたは(先頭にアンダースコアで)_popen
に言及
[リダイレクトされた入力と出力を持つ子プロセスを作成する](https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499.aspx) tasklist.exeの入出力をリダイレクトする必要があります。次に、クライアントからコマンドを読み込んでプロセスに送信し、応答を読み込んでクライアントに返します。 –