您的位置:首页 > 其它

get IP address of a given machine

2013-11-18 09:50 381 查看
getaddrinfo在linux man page中的详细解释:

http://linux.die.net/man/3/getaddrinfo

/* homework1_getaddr:get the IP addresses of a given machine */

#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <netinet/in.h>

struct addrinfo hints,*result,*a;
struct timeval start,end;
struct hostent *hptr;

int main(int argc,char *argv[])
{
//to figure out if the hostname is inserted correctly
if(argc!=2)
{
printf("Please insert the hostname.\n");
return 1;
}

//memory set and define values for hints
bzero(&hints,sizeof(hints));
hints.ai_family=AF_INET;
hints.ai_socktype=SOCK_STREAM;

//to figure out if the hostname is valid
int addrinforeturn=0;
gettimeofday(&start,NULL);
if (addrinforeturn!=getaddrinfo(argv[1], NULL, &hints, &result))
{
printf("Please check if you insert correctly\n");
return 2;
}
gettimeofday(&end,NULL);

//to print the execution time
unsigned long usedtime=1000*(end.tv_sec-start.tv_sec)+(end.tv_usec-start.tv_usec)/1000;
printf("execution time:%u milliseconds\n",usedtime);

//to print the official name from the gethostbyname function
hptr=gethostbyname(argv[1]);
printf("official name:%s \n",hptr->h_name);

//to print the aliases if it really has
char **aptr;
for(aptr=hptr->h_aliases;*aptr!=NULL;aptr++)
printf("Aliases:%s\n",*aptr);

//to convert the IP to a string and print the addresee
for (a=result; a!=NULL; a=a->ai_next)
{
void *addr;
char ipaddr[INET_ADDRSTRLEN];//address string length for ip
struct sockaddr_in *ip=(struct sockaddr_in *)a->ai_addr;//transfer the struct type from scokaddr to scokaddr_in
addr=&(ip->sin_addr);
inet_ntop(AF_INET, addr, ipaddr, sizeof(ipaddr));//convert the type of the address
printf("%s\n",ipaddr);
}

//clear memory for the linked list
freeaddrinfo(result);
return 0;
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: