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

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

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值