解析域名与IP地址(Linux编程)

来源:互联网 发布:央视新闻客户端 mac 编辑:程序博客网 时间:2024/05/22 02:10

 

 

<!--@page { size: 8.5in 11in; margin: 0.79in }P { margin-bottom: 0.08in }-->

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <assert.h>
#include <string.h>
#include <netdb.h>

#define ERROR(format, args...) fprintf(stderr, format, ##args)
void getHost(const char *url, char *host);
void getIP(const char *host, char *ip, size_t n);

int main(int argc, char *argv[])
{
if(argc !=2 )
{
ERROR("Usage: %s url", argv[0]);
return -1;
}
char *host = (char*)malloc(sizeof(char) * (strlen(argv[1]) + 1));
char *ip = (char*)malloc(sizeof(char) * 16);
getHost(argv[1], host);
getIP(host, ip, 16);
printf("Host: %s/nIP: %s/n", host, ip);
free(ip);
free(host);
return 0;
}

void getHost(const char *url, char *host)
{
char *p = strstr(url, "://");
if(p)
{
strcpy(host, p + 3);
}
else
{
strcpy(host, url);
}
p = strstr(host, "/");
if(p)
{
*p = '/0';
}
}

void getIP(const char *host, char *ip, size_t n)
{
struct hostent *he = gethostbyname(host);
assert(he);
assert(inet_ntop(AF_INET, he->h_addr_list[0], ip, n)); //只取第1个IP地址
}