<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()
~
两个函数就搞定了,当然底层的代码都封装了的原因的吧,就这样啦~