温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

获取设备的主机名和ip地址

发布时间:2020-07-21 13:52:15 来源:网络 阅读:1688 作者:祥波 栏目:开发技术

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

源代码如下

#!/usr/bin/env python
#This program is optimized for python 2.7 .It may run on any
#other python version with/without modifications.
#Failname:local_machine_info.py

import socket

def print_machine_info():
    host_name=socket.gethostname()
    ip_address=socket.gethostbyname(host_name)
    print "Host name : %s" %host_name
    print "IP address: %s" %ip_address

if __name__=='__main__':
    print_machine_info()

执行结果:

获取设备的主机名和ip地址


原理分析:


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

获取设备的主机名和ip地址

获取设备的主机名和ip地址


获取设备的主机名和ip地址

获取远程设备的IP地址

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

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

#!/usr/bin/env python
#This program is optimized for python 2.7
#It may run on any other version with/without modifications
#Filename:remote_machine_info.py

import socket
def get_remote_matchine_info():
    remote_host='www.51cto.com'
    try:
        print " remote_host is:%s"%remote_host
        print "IP address:%s"%socket.gethostbyname(remote_host)
    except socket.error,err_msg:
        print "%s:%s"%(remote_host,err_msg)

if __name__=='__main__':
    get_remote_matchine_info()


执行结果:

获取设备的主机名和ip地址

原理分析:

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


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI