0

I need to create a simple http client to a web server and my code is the following:

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <arpa/inet.h>

struct sockaddr_in wserver, cl;
struct hostent *rem;
int fd, newfd, len, l;

int main(int argc, char *argv[])
{
 wserver.sin_family = AF_INET;
 wserver.sin_port = 0;//htons(9780);
 //wserver.sin_addr.s_addr = inet_addr(rem->h_addr);
 wserver.sin_addr.s_addr = inet_addr(argv[1]);
 rem = gethostbyname(argv[1]);
 memcpy(&wserver.sin_addr, rem->h_addr_list[0], rem->h_length);
 
 if((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
 {
  perror("create socket");
  exit(1);
 }


 if(connect(fd, (struct sockaddr*)&wserver, sizeof(wserver)) < 0)
 {
  perror("connect");
  exit(1);
 }

  printf("CONNECTED!!!!!!\n");
 
 return 0;
}

I am working with terminal and the errors i get are:

No route to host

or

Connection refused

or

Connection timed out

all coming from connect

2
Contributors
2
Replies
5
Views
5 Years
Discussion Span
Last Post by SpyrosMet
0

Never mind. I figured it out. It was supposed to run through port 9780 but it couldn't so i set it to 0 to pick a port randomly. Anyway I needed to connect to a web site host so the right port was 80. Sorry for the inconvinience.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.