获取IP地址函数(本地、域名转换)

来源:互联网 发布:软件著作权是什么 编辑:程序博客网 时间:2024/06/05 19:17
/* GetIp.c -- Get Local or remote Ip address by domain name* */

#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

#include <s

/*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
}