擷取IP地址函數(本地、網域名稱轉換)

來源:互聯網
上載者:User
/* 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
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.