I created a C program that will make a connection to a website. I can compile it with no errors at all but when I run it, I still can't create a connection to my specified website. The errors that are shown in the terminal are:
client: connect: Connection timed out
client: connect: Connection timed out
client: failed to connect
Right now I can't find where the error might be. So may I ask anyone if there is something erroneous/missing in the program? Thank you.
My program looks like the one below:
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main()
{
struct addrinfo hints, *res, *p;
int sockfd, status;
char s[INET6_ADDRSTRLEN];
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo("www.yahoo.com", "8080", &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
return 2;
}
for (p = res; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("client: connect");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "client: failed to connect\n");
return 2;
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
printf("Successfully connected to: %s.\n", s);
freeaddrinfo(res);
close(sockfd);
return 0;
}