2008年4月16日 星期三

研發筆記-利用Hostname反查IP的小程式

事件:有時候只知道Hostname,但當我們要connect,或是要做一些比對的時候,卻又需要ip address,因此利用gethostbyname()來取得IP。
程式碼如下:

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

int main(int argc, char **argv)
{
int i,j;
for(i=1; i<argc; i++)
{
struct hostent *ht;

ht = gethostbyname(argv[i]);

if(!ht)
{
printf("error\n");
continue;
}

printf("host =%s\n",argv[i]);

if(ht->h_addrtype == AF_INET)
{
for(j=0;ht->h_addr_list[j];j++)
printf("address: %s\n",inet_ntoa(*(struct in_addr *)ht->h_addr_list[j]));
}
}
return 0;
}

執行範例:
[root@ATC-P4-95 UPC]# ./test2 tw.yahoo.com
host =tw.yahoo.com
address: 203.84.202.164

2 意見:

匿名 提到...
網誌管理員已經移除這則留言。
匿名 提到...
網誌管理員已經移除這則留言。