Hi everyone! I'm trying to make a C code in Linux that will create a connection to a specific website. My goal is to have a program that will ask for an input, and depending on the input's value, the program will invoke a connection to a website. For example, if the input is 1, the program will connect to
www.yahoo.com. The website that the program will connect to will be pre-determined, which means that whenever the input is 1 the program will try to connect to
www.yahoo.com only, no random choosing of websites will be done.
So far, I've created a simple program to try to connect to
www.yahoo.com. I can compile it with no errors, but when I run it, these errors are seen in the terminal:
client: connect: Connection timed out
client: connect: Connection timed out
client: failed to connect
I really don't know if I missed to put anything and I can't debug the program anymore so I hope someone here could help me solve this. Thank you.
The source code looks like the one below:
Code:
// 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;
}