C socket problems

0

I have 3 functions responsible for creating a socket, sending data and receiving data. The function sock_create creates a new socket returning an int from this socket, the function sock_send sends a header to the sockfd (server), and finally the function sock_recv that is responsible for the data splitting, has as argument the sockfd int (created by the function sock_create). Here follows the code and just below the question.

#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
//#include <unistd.h>
#include <string.h>

char *DEFAULT_GET = "GET /index.html HTTP/1.1\r\nHost: 
www.example.com\r\n\r\n";

void sock_send(int, char *);
char* sock_post(int, char *);
char* sock_recv(int, int);
int sock_create(char*);
char* getline();

int main()
{
    char url[200];
    memset(url, 0, sizeof url);
    printf("Enter URL: \n");
    scanf("%s", url);
    url[strlen(url)] = 0;
    printf("%s\n", url);
    int sockfd = sock_create(url);
    printf("socket created\n");

    while (1)
    {
        printf("send a request: \n");
        char header[200];
        memset(header, 0, 200);
       //scanf("%s", header);
        sock_send(sockfd, DEFAULT_GET);
        char *resp = sock_recv(sockfd, 2048);

        printf("%s\n", resp);
    }

    return 0;
}

void sock_send(int sockfd, char *header)
{
    send(sockfd,header,strlen(header),0);
    printf("sock_send: sockfd[%d], header[]\n", sockfd);
}

char* sock_recv(int sockfd, int buf_bytes)
{
    char buf[buf_bytes];
    int byte_count = recv(sockfd, buf, sizeof(buf) - 1, 0);
    buf[byte_count] = 0;

    printf("sock_recv: count[%d]\n", byte_count);

    return buf;
}

char* sock_post(int sock, char *post_header)
{

}

int sock_create(char *url)
{
    struct addrinfo hints, *res;

    memset(&hints, 0,sizeof hints);

    hints.ai_family=AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    getaddrinfo(url,"80", &hints, &res);
    int sockfd = socket(res->ai_family,res->ai_socktype,res-
  >ai_protocol);

    connect(sockfd,res->ai_addr,res->ai_addrlen);
    printf("sock created\n");

    return sockfd;
}

When I run the code I get a message: You have stoped jobs, which I believe is the same as segmentation fault. Anyway, I do not know why that error.

    
asked by anonymous 14.07.2018 / 16:45

1 answer

0

You should define everything correctly in the prototype:

void sock_send(int sockfd, char * header);
char* sock_post(int sockfd, char * post_header);
char* sock_recv(int sockfd, int  buf_bytes);
int sock_create(char*);

This was the error that was causing problems! (I tested here, compiled it and it worked fine)

.

Ready, I hope I have helped!

    
26.07.2018 / 08:38