Hi there,

I am trying to write a program to send an HTTP request (eventually to view the raw HTML page) but i can't seem to get my requests to send or receive properly, intially when i ran this it would receive about 4190000 bytes (rough guess) but after running it a few times it now receives 0 bytes and i get the following output:

Unable to connect: Socket operation on non-socket
Error sending: Bad file descriptor
1 BYTES SENT.
Error: Bad file descriptor
-1 BYTES RECIEVED.

It seems strange that it was intially able to send data....... although i may have accidentally edited something.

Any ideas? I'm presuming its my code :(

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


int main(){

struct addrinfo hints, *res;
int sockfd;

// first, load up address structs with getaddrinfo():

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;  // use IPv4 or IPv6, whichever
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;     // fill in my IP for me

getaddrinfo("www.example.com", "80", &hints, &res);

// make a socket:

if (sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol) == -1)
	perror("Unable to create socket");

// bind it to the port we passed in to getaddrinfo():

if (connect(sockfd, res->ai_addr, res->ai_addrlen) == -1){
	perror("Unable to connect");
	close(sockfd);
}

// send request
char *msg = "GET /index.html HTTP/1.1\r\n Host: www.example.com\r\n";
int len, bytes_sent;

len = strlen(msg);
if (bytes_sent = send(sockfd, msg, len, 0) == -1)
	perror("Error sending");

printf("%d",bytes_sent);
printf(" BYTES SENT.\n");


//recieve response
ssize_t i;
ssize_t rcount;
char buf[1500];

rcount = read(sockfd, buf, 1500);
if (rcount == -1)
	perror("Error");

printf("%d", rcount);
printf(" BYTES RECIEVED.\n");

for (i = 0; i < rcount; i++){
	printf("%c", buf[i]);

}
}

Well, the error tells you that it can't create the connection because the socket descriptor is not a socket. Have a look at the possible reasons for that. Perhaps you still have a identical socket floating around in a previous unstopped run?

Please take your time to study curl library (source code) where you can find a simple example to understand how to post a http request with C programming.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.