|
楼主 |
发表于 2004-11-4 04:09:22
|
显示全部楼层
实现获取ip的代码
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
int main(int argc,char **argv) {
struct hostent *answer;
struct in_addr address,** addrptr;
char **next;
if (argc !=2){
fprintf(stderr,"only a single argument is supported\n");
return 1;
}
if (inet_aton(argv[1],&address))
answer=gethostbyaddr((char *)&address,sizeof(address),AF_INET);
else
answer=gethostbyname(argv[1]);
if(!answer){
herror("error looking up host");
return 1;
}
printf("canonical hostname:%s\n",answer->h_name);
if (answer->h_aliases[0]){
printf("Aliases:");
for (next=answer->h_aliases;*next;next++)
printf("%s,*next");
printf("\n");
}
printf("Addresses:");
for (addrptr=(struct in_addr **) answer->h_addr_list;*addrptr;addrptr++)
printf("%s",inet_ntoa(**addrptr));
printf("\n");
return 0;
} |
|