C语言获取主机名和IP地址

19 篇文章 3 订阅
19 篇文章 0 订阅

获取主机与IP地址的C语言代码
我们将使用以下函数:
gethostname():gethostname函数检索本地计算机的标准主机名。
gethostbyname():gethostbyname函数从主机数据库中检索与主机名对应的主机信息。
inet_ntoa():inet_ntoa函数将(Ipv4)Internet网络地址转换为Internet标准点分十进制格式的ASCII字符串。

  1 #include <stdio.h> 
  2 #include <stdlib.h>
  3 #include <unistd.h>
  4 #include <errno.h>
  5 #include <netdb.h>
  6 #include <sys/types.h>
  7 #include <sys/socket.h>
  8 #include <netinet/in.h>
  9 #include <arpa/inet.h>
 10 
 11 //返回本地主机名
 12 void checkHostName(int hostname){
 13     if(hostname == -1){
 14         perror("gethostname");
 15         exit(1);
 16     }
 17 }
 18 
 19 //返回主机对应的信息到主机名
 20 void checkHostEntry(struct hostent *hostentry){
 21     if(hostentry == NULL){
 22         perror("gethostbyname");
 23         exit(1);
 24     }
 25 }
 26 
 27 //将Ipv4地址格式转化为点分十进制
 28 void checkIPbuffer(char *IPbuffer){
 29     if(NULL == IPbuffer){
 30         perror("inet_ntoa");
 31         exit(1);
 32     }
 33 }
 34 
 35 //设备代码
 36 int main(){
 37     char hostbuffer[256];
 38     char *IPbuffer;
 39     struct hostent *host_entry;
 40     int hostname;
 41 
 42     //接收主机名
 43     hostname = gethostname(hostbuffer, sizeof(hostbuffer));
 44     checkHostName(hostname);
 45 
 46     //接收主机信息
 47     host_entry = gethostbyname(hostbuffer);
 48     checkHostEntry(host_entry);
 49 
 50     //转换网络地址
 51     IPbuffer = inet_ntoa(*((struct in_addr*)
 52                 host_entry->h_addr_list[0]));
 53     printf("Hostname: %s\n", hostbuffer);
 54     printf("Host IP: %s\n", IPbuffer);
 55 
 56 
 57     return 0;
 58 }

  • 9
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值