我是c的新手,尤其是插座,如果这个问题很愚蠢,我很抱歉。这是我的代码:
/****************** SERVER CODE ****************/
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
int main(){
int welcomeSocket, newSocket;
char buffer[1024];
struct sockaddr_in serverAddr;
struct sockaddr_storage serverStorage;
socklen_t addr_size;
welcomeSocket = socket(PF_INET, SOCK_STREAM, 0);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(7891);
serverAddr.sin_addr.s_addr = 0;
memset(serverAddr.sin_zero, '\0', sizeof(serverAddr.sin_zero));
bind(welcomeSocket, (struct sockaddr *) &serverAddr,
sizeof(serverAddr));
if(listen(welcomeSocket,5)==0)
printf("Listening\n");
else
printf("Error\n");
addr_size = sizeof serverStorage;
newSocket = accept(welcomeSocket,
(struct sockaddr *) &serverStorage, &addr_size);
strcpy(buffer,"Hello World\n");
send(newSocket,buffer,13,0);
memset(buffer, '\0', 1024);
while(recv(newSocket, &buffer, 1024, 0) > 0)
{
printf("%s", system(buffer));
memset(buffer, '\0', 1024);
}
return 0;
}
这是我的服务器,我正在使用telnet连接(我知道它不安全,任何用户在服务器中执行任何命令都不是用于教育目的)。当我输入“ls”(服务器程序在linux上运行)时,它会让我回复此错误未找到 分段错误(核心转储)并断开连接。我希望你能提供帮助。感谢
答案 0 :(得分:3)
由于这一行,您的程序崩溃了:
printf("%s", system(buffer));
如此处所述:http://linux.die.net/man/3/system
system()
调用返回一个整数,而不是char *。
根据您的需要,您可以使用popen()
。
请参阅此问题的答案以获取示例:
How to execute a command and get output of command within C++ using POSIX?
要么
How to get the output of grep in C