Socket Programming - Trouble Connecting to HTTP Server
I've written a program that should establish a connection with a remote HTTP server, send it a request, and then print a response to the standard output.
However, for some reason I cannot connect my socket. I have been around multiple sites and they each say that I'm doing everything right, so I'm not sure what's going on. I've posted my code below.
I keep getting `Connection attempt failed. Program terminating...`
Code:
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
FILE *fout;
int c, sk;
char *tk, host[64], path[64], fname[64], http_msg[256], buf[1024];
struct sockaddr_in remote;
struct hostent *hp;
struct servent *se;
if(argc != 2)
{
printf("Invalid number of arguments. Program terminating...\n");
exit(1);
}
sk = socket(AF_INET, SOCK_STREAM, 0);
if(sk == -1)
{
printf("Error opening socket. Program terminating...\n");
exit(1);
}
c = 0;
tk = strtok(argv[1], "/");
while(tk != NULL)
{
if(c == 0)
strcpy(host, tk);
else if(c == 1)
strcpy(path, tk);
else
strcpy(fname, tk);
++c;
tk = strtok(NULL, "/");
}
snprintf(http_msg, 256, "GET /%s/%s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", path, fname, host);
hp = gethostbyname(host);
if(hp == NULL)
{
printf("Can't find host %s. Program terminating...\n", host);
exit(1);
}
remote.sin_family = AF_INET;
bcopy((char *)hp->h_addr, (char *)&remote.sin_addr.s_addr, hp->h_length);
se = getservbyname("http", "tcp");
remote.sin_port = htons(se->s_port);
if(connect(sk, (struct sockaddr *)&remote, sizeof(remote)) == -1)
{
printf("Connection attempt failed. Program terminating...\n");
exit(1);
}
send(sk, http_msg, sizeof(http_msg) + 1, 0);
recv(sk, buf, sizeof(buf), 0);
printf("%s\n", buf);
fout = fopen(fname, "w");
write(fout, buf, 1024);
fclose(fout);
close(sk);
return 0;
}