get IP address of a given machine

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;
}
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值