Python的socket模块提供了类的方法和实例方法,二者区别在于使用类方法时不需要创建套接字对象实例。比如,以下例子利用此模块获取主机名和ip地址。

源代码如下

#!/usr/bin/envpython#Thisprogramisoptimizedforpython2.7.Itmayrunonany#otherpythonversionwith/withoutmodifications.#Failname:local_machine_info.pyimportsocketdefprint_machine_info():host_name=socket.gethostname()ip_address=socket.gethostbyname(host_name)print"Hostname:%s"%host_nameprint"IPaddress:%s"%ip_addressif__name__=='__main__':print_machine_info()

执行结果:


原理分析:


本例程调用了socket中的两个工具函数gethostname()和gethostbyname()。可以使用help()函数查看帮助信息。



获取远程设备的IP地址

使用内置的库函数gethostbyname()可以获取远程设备的ip地址,函数的参数为目标主机的主机名。

以远程主机名为www.51cto.com为例,代码如下:

#!/usr/bin/envpython#Thisprogramisoptimizedforpython2.7#Itmayrunonanyotherversionwith/withoutmodifications#Filename:remote_machine_info.pyimportsocketdefget_remote_matchine_info():remote_host='www.51cto.com'try:print"remote_hostis:%s"%remote_hostprint"IPaddress:%s"%socket.gethostbyname(remote_host)exceptsocket.error,err_msg:print"%s:%s"%(remote_host,err_msg)if__name__=='__main__':get_remote_matchine_info()


执行结果:

原理分析:

本例将主要的函数调用放在了try-except块中,如果gethostbyname()函数执行的过程中发送了错误,这个错误将由try-except块处理,提示错误信息。