Search code examples
csocketsserversocket

error when connecting server and using system function in c


I'm new in c and especially in sockets and if this question is silly i'm sorry. Here is my code:

/****************** 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;
}

This is my server and i'm connecting with telnet(I know its not secure and let any user execute any command in server is neither but its for educational purposes). when i type "ls"(server program is run on linux) it gives me back this error not found Segmentation fault (core dumped) and disconnects me. I hope you can help. thanks


Solution

  • Your program is crashing because of this line:

    printf("%s", system(buffer));
    

    as stated here: http://linux.die.net/man/3/system the system() call is returning an integer, not a char*.

    for what you want, you could use popen(). see the answer on this question for an example: How to execute a command and get output of command within C++ using POSIX? or How to get the output of grep in C