-
gethostbyname
Consider this code:
Code:
#include <stdio.h>
#include <string.h>
#include <Winsock2.h>
int main(int argc, char *argv[])
{
struct hostent *h;
if(argc !=2)
{
fprintf(stderr,"Argument error!");
exit(1);
}
h=gethostbyname(argv[1]);
if(h==NULL)
{
fprintf(stderr,"gethostbyname error!");
exit(1);
}
printf("\nHost name: %s",h->h_name);
printf("IP adress: %s",inet_ntoa(*((struct in_addr *)h->h_addr)));
}
This also an example from Beej's tutorial.
Of coure that I'll get error "gethostbyname error!"
I don't know what is the purpose of this example.
This, just like other examples simply don't work.
Maybe I'm doing something wrong?
After server and telnet example this happened.
It's seems that networking is simply too hard (not to understand, but to make it work)!
If someone can explain me what I'm doing wrong (except the decision to learn this)
-
You need to initialize winsock before using any winsock function:
Code:
int main(int argc, char *argv[])
{
struct hostent *h;
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
printf("Failed to initialize!\n");
return -1;
}
if(argc !=2)
{
fprintf(stderr,"Argument error!");
exit(1);
}
h=gethostbyname(argv[1]);
if(h==NULL)
{
fprintf(stderr,"gethostbyname error!");
exit(1);
}
printf("\nHost name: %s",h->h_name);
printf("IP adress: %s",inet_ntoa(*((struct in_addr *)h->h_addr)));
}
-
I did it, but error was that I entered in command line:
"http://..."
Sorry for trouble
-
You can't enter "http://". The "http://" tells a browser that the url is using the http protocol(rather than ftp for example, which uses "ftp://"). It is not part of the server name.
Here are some valid server names:
cboard.cprogramming.com
alltheweb.com
www.cprogramming.com