前些天由于项目需要,自己整了一个比较全面的获取IP地址的函数:可以获取本地的IP地址,也可以根据域名获取IP地址,感觉比较有用特此奉献上,呵呵。
下面是源代码
/* GetIp.c -- Get Local or remote Ip address by domain name * Designed by falcon, 2006-9-16, Email: zhangjinw[at]gmail.com * */
#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; }
下面是一个测试的代码 test_GetIp.c
/*test_GetIp.c*/ #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; }
具体使用演示
$./test_GetIp xxxy.lzu.edu.cn --这里是根据域名转换为IP地址 domain name or ip address : xxxy.lzu.edu.cn current ip address: 202.201.0.237
$ ./test_GetIp 219.246.79.7 --输入地址返回地址 domain name or ip address : 219.246.79.7 current ip address: 219.246.79.7
$ ./test_GetIp localhost --获取本地IP地址 domain name or ip address : localhost current ip address: 219.246.79.4
(iwgh) |