Problems with C socket

Asked

Viewed 81 times

0

I have 3 functions responsible for creating a socket, sending data and receiving data. Function sock_create creates a new socket by returning an int of that socket, Function sock_send sends a header to sockfd(server), and finally Function sock_recv which is responsible for data riveting, has as its argument the int sockfd (created by 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 execute the code I get a message: You have stoped Jobs, which I believe is the same as Segmentation fault. Anyway, I don’t know why I made a mistake.

1 answer

2


You must set 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 it here, compiled it and worked right)

.

Okay, I hope I helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.