954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

http client can't connect to web server

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

SpyrosMet
Light Poster
46 posts since Feb 2010
Reputation Points: 7
Solved Threads: 3
 
wserver.sin_port = 0;

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

harinath_2007
Posting Whiz
355 posts since Aug 2010
Reputation Points: 78
Solved Threads: 36
 

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.

SpyrosMet
Light Poster
46 posts since Feb 2010
Reputation Points: 7
Solved Threads: 3
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: