Hello There, I am trying to change a simple client code that will retrieve the web pages from any web site using TCP sockets. It fails in the connect function.
When I made the code run on my m/c (with a server), it worked fine but it doesnt create connection to other web sites like google and all. I have a similar Java code that works but don't know where exactly am I going wrong.
I am running it on a 64 bit AMD Turion X2 with Ubuntu 9.10
Code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#define MAXRCVLEN 500
#define PORTNUM 80
int main(int argc, char *argv[])
{
char buffer[MAXRCVLEN + 1];
int len, mysocket;
struct sockaddr_in dest;
int ret;
struct hostent * hinfo;
char * sname;
if (argc > 1)
{sname=argv[1];}
else
{sname="cprogramming.com";}
mysocket = socket(AF_INET, SOCK_STREAM, 0);
memset(&dest, 0, sizeof(dest));
dest.sin_family = AF_INET;
hinfo = gethostbyname(sname);
if(hinfo == NULL) {printf("getbyname failed!\n");}
dest.sin_addr.s_addr = inet_addr(hinfo->h_addr);
dest.sin_port = htons(PORTNUM);
ret = connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr));
printf("Connection status:%d\n", ret); /* ret is -1 here*/
len = recv(mysocket, buffer, MAXRCVLEN, 0);
buffer[len] = '\0';
close(mysocket);
return EXIT_SUCCESS;
}