Python网络编程 ---Socket模块学习之获取远程设备IP(二)
1、使用内置库函数gethostbyname(),参数为远程设备的主机名。新建文件 getremotemachineinfo.py#!/usr/bin/pythonimport socketdef get_remote_machine_info(): remote_host_name = 'www.baidu.com' try: print "IP Addres
·
1、使用内置库函数gethostbyname(),参数为远程设备的主机名。新建文件 getremotemachineinfo.py
#!/usr/bin/python
import socket
def get_remote_machine_info():
remote_host_name = 'www.baidu.com'
try:
print "IP Address: %s" %socket.gethostbyname(remote_host_name)
except socket.error, err_msg:
print " %s:%s" %(remote_host_name, err_msg)
if __name__ == '__main__':
get_remote_machine_info()
$ python getremotemachineinfo.py
IP Address: 220.181.112.244
原理分析:
把gethostbyname()方法包装在用户定义的函数get_remote_machine_info()中。引入异常处理概念,主要的函数放在try中,意味着执行和三叔的过程中如果发生了错误,则这个错误将会交给except处理。如果上述中,我们输入www.bad.com.则出现以下效果:
www.pytgon.com:[Errno -5] No address associated with hostname
更多推荐
已为社区贡献1条内容
所有评论(0)