网络编程之获取主机名称与IP地址
2015-07-02 20:28
465 查看
<p style="font-size: 13.3333339691162px;">写这个的缘由在于最近在看python网络编程攻略这本书,所以记录自己的学习过程,由于python是由C实现的,所以很多的函数发现在C中也有,所以也查阅资料(不乏抄袭代码)用C实现了一下,干脆把两种实现同时post在这吧</p><p style="font-size: 13.3333339691162px;"></p><p style="font-size: 13.3333339691162px;">首先上C的代码</p><div> </div>#include<netdb.h> //#include<sys/socket.h> #include<unistd.h> #include<stdio.h> #include<string.h> #include<memory.h> #include<arpa/inet.h> /* * struct hostent * { * char *h_name; //主机的规范名称 * char **h_aliases; //主机的别名 * int h_addrtype; //iP地址类型(AF_INET或者AF_INET6) * int h_length; //IP长度 * char **h_addr_list; //IP列表 * #define h_addr h_addr_list[0] * }; */ int main(int arc, char** argv) { char hostname[32]; char str[32]; struct hostent* hostInfo; //int gethostname(char *name,int namelen); //此函数返回设备名,并保存在*name中,namelen是*name的长度,成功返回0,否则返回SOCKET_ERROR,本人懒,没有捕获异常 gethostname(hostname,sizeof(hostname)); printf("localhost name:%s\n",hostname); //gethostbyname获取主机的其他信息,返回一个hostent结构体 hostInfo=gethostbyname(hostname); printf("official host name %s\n",hostInfo->h_name); printf("alias: "); char** strptr=hostInfo->h_aliases; for(;*strptr != NULL;strptr++) printf("%s ",*strptr); printf("\n"); char IPtype[9]; //h_addrtype是一个整数,为了直观,将其变成对应的字符串吧 switch(hostInfo->h_addrtype) { case AF_INET: strcpy(IPtype,"AF_INET"); break; case AF_INET6: strcpy(IPtype,"AF_INET6"); break; default: { char temp='0'+hostInfo->h_addrtype; strcpy(IPtype,&temp); break; } } printf("IP type: %s\n",IPtype); printf("length: %d\n",hostInfo->h_length); printf("addr list:"); strptr=hostInfo->h_addr_list; for(;*strptr !=NULL;strptr++) { //const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) h_addr_list是网络字节序的形式,需要对应的转换为主机字节序的形式,用inet_ntop inet_ntop(hostInfo->h_addrtype,*strptr,str,sizeof(str)); printf("%s ",str); memset(str,0,sizeof(str)); } printf("\n"); return 0; }
OK,你可以自己跑一下看自己的主机名和IP地址啦
相应的python代码就显得简单的多了
#!/usr/bin/env python #-*- coding: utf-8 -*- import socket def print_machine_info(): #get host_name host_name = socket.gethostname() #get ip_address ip_address = socket.gethostbyname(host_name) #print the machine_info print "host name: %s" %host_name print "ip address: %s" %ip_address if __name__=='__main__': print_machine_info() ~两个函数就搞定了,当然底层的代码都封装了的原因的吧,就这样啦~
相关文章推荐
- DSAPI多功能组件编程应用-HTTP监听服务端与客户端
- 网络编程 select epoll
- TCP 组播 广播
- Android网络编程中关于AsyncHttpClient获取cookie的问题
- 【Web探索之旅】第三部分第二课:IP地址和域名
- 【Web探索之旅】第三部分第一课:服务器
- [Http] cookie和session
- 获取网络图片
- Java基础 网络编程 Socket UDP TCP URL
- TCP常见问题FAQ
- juno dashboard创建网络,ping 通百度
- 网络请求2种方法
- Indy TIdTCPClient伪非阻塞式的解决方案
- 【Web探索之旅】第二部分第二课:服务器语言
- 【Web探索之旅】第一部分:什么是Web?
- 如何获取手机上网时的外部网络的IP地址
- Android三种基本的加载网络图片方式
- 统计内网机器网络流量的方案
- HTTP认证方式
- TCP closing a connection