I am coding something to find web servers. It is in C.
I have this
sprintf(pre_ip, "%d.%d.%d.%d", num1, num2, num3, num4);
num1-4 is an ip like 1.1.1.1. This part works..
he = gethostbyname(pre_ip);
This should assign struct hostent *he; to the ip..
but this doesnt work..
server_info.sin_addr = *((struct in_addr *)he->h_addr);
connect(socket_fd, (struct sockaddr *)&server_info, sizeof(struct sockaddr));
Here is the whole code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
//lol220
int main(int argc, char *argv[])
{
struct sockaddr_in server_info;
struct hostent *he;
int socket_fd,num;
char buffer[1024];
char buff[1024];
if (argc != 1) {
fprintf(stderr, "Usage: client hostname\n");
exit(1);
}
if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0))== -1) {
fprintf(stderr, "Socket Failure!!\n");
exit(1);
}
memset(&server_info, 0, sizeof(server_info));
server_info.sin_family = AF_INET;
server_info.sin_port = htons(80);
//-------------------------------looooop------------------------
int num1 = 1;
int num2 = 1;
int num3 = 1;
int num4 = 1;
int done = 1;
char ip;
char pre_ip[256];
while(done){
if(num4 == 256){
num4 = 1;
num3++;
}
if(num3 == 256){
num3 = 1;
num2++;
}
if(num2 == 256){
num2 = 1;
num1++;
}
if(num1 == 255 && num2 == 255 && num3 == 255 && num4 == 255){
done = 0;
}
// MOST LIKELY NON WORKING PART
sprintf(pre_ip, "%d.%d.%d.%d", num1, num2, num3, num4);
printf("%s\n", pre_ip);
he = gethostbyname(pre_ip);
server_info.sin_addr = *((struct in_addr *)he->h_addr);
if (connect(socket_fd, (struct sockaddr *)&server_info, sizeof(struct sockaddr))<0) {
printf("Could not connect to %s", he);
}
else{
printf("Could connect to %s", he);
}
// MOST LIKELY NON WORKING PART
num4++;
}
return 0;
}
It compiles fine.
prints "1.1.1.1" then it says "Could not connect to 8T1.1.1.2" so that means he == "8T1.1.1.2.