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

Recommended Answers

All 2 Replies

wserver.sin_port = 0;

Is server running on port 0? specify correct port number and try again..

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.

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.