2007-3-7 09:06
问天
Linux下 根据域名获取IP地址
Text
下面这个用C语言写的函数,可以用来在Linux下获取本地IP地址或者通过域名获取IP地址。
我使用的操作系统是Ubuntu 6.06。
Code
[1] Function -- GetIp.c
[code]
/* filename: GetIp.c
* function: Get local ip Or Get ip by domain name
* author: falcon
* email: zhangjinw[at]gmail.com
* date: 2006-9-16
*/
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#define h_addr h_addr_list[0]
char *
GetIp(char *dn_or_ip)
{
struct sockaddr_in addr;
struct hostent *host;
struct ifreq req;
int sock;
if (dn_or_ip == NULL) return NULL;
if (strcmp(dn_or_ip, "localhost") == 0) {
sock = socket(AF_INET, SOCK_DGRAM, 0);
strncpy(req.ifr_name, "eth0", IFNAMSIZ);
if ( ioctl(sock, SIOCGIFADDR, &req) < 0 ) {
printf("ioctl error: %s\n", strerror (errno));
return NULL;
}
dn_or_ip = (char *)inet_ntoa(*(struct in_addr *) &((struct sockaddr_in *) &req.ifr_addr)->sin_addr);
shutdown(sock, 2);
close(sock);
} else {
host = gethostbyname(dn_or_ip);
if (host == NULL) return NULL;
dn_or_ip = (char *)inet_ntoa(*(struct in_addr *)(host->h_addr));
}
return dn_or_ip;
}
[/code]
[2] Example -- test_GetIp.c
[code]
#include <stdio.h>
#include "GetIp.c"
int
main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "Usage: %s domain_name or ip_address\n", argv[0]);
return -1;
}
char *current_ip_address;
current_ip_address = NULL;
if ((current_ip_address = GetIp( argv[1])) == NULL) {
printf ("Ip address convert error!\n");
return -1;
} else {
printf("domain name or ip address : %s\n", argv[1]);
printf("current ip address: %s\n", current_ip_address);
}
return 0;
}
Demo
shell> gcc -o test_GetIp test_GetIp.c
shell> ./test_GetIp localhost
domain name or ip address : localhost
current ip address: 219.246.79.72
shell> ./test_GetIp www.chinaunix.net
domain name or ip address : www.chinaunix.net
current ip address: 60.28.166.84
[/code]
Extention
我最初写这个函数的目的,是为了使用到FTP Search Engine里头。为了实现FTP的两种数据交互模式,PASV和PORT模式,就必须获取本地的IP地址和服务器的IP地址(在只知道服务器域名的情况下)。当然,也许还有其他的用途哦。希望能对你有帮助。