gethostbyname:根据主机名获取ip
gethostbyaddr:根据ip获取主机名
示例如下:
#include "net_common.h"
int main()
{
char *name = "localhost";
//INET_ADDRSTRLEN值为16,用来标识ipv4地址长度
char str[INET_ADDRSTRLEN];
//根据主机名获取ip
struct hostent *hptr = gethostbyname(name);
if(hptr == NULL)
{
hstrerror(h_errno);
}
//hostent中的h_addr_list是一个数组
char **pptr = hptr->h_addr_list;
for(; *pptr != NULL; pptr++)
{
//将ip保存在str中并打印。
puts(inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
}
//清空结构体,以便再次使用
memset( hptr, 0, sizeof(struct hostent));
hptr = NULL;
//将ip转为网络地址格式
int nip = inet_addr(str);
//使用gethostbyaddr需将网络地址格式的ip转为字符串类型
hptr = gethostbyaddr((char *)&nip, INET_ADDRSTRLEN, AF_INET);
if(hptr == NULL)
{
hstrerror(h_errno);
}
//打印主机名
puts(hptr->h_name);
return 0;
}
因为每次都需要写头文件,所以将一些常用的头文件整理了放在net_common.h中,内容如下:
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
//一个常用的错误检查函数
void check(char * fname)
{
if(errno==-1)
{
perror(fname);
exit(EXIT_FAILURE);
}
}