python网络编程之网络主机信息

功能: 获取设备名称
方法: gethostname()
参数返回值:hostname(string)


功能: 获取设备ipv4地址
方法: gethostbyname()
参数: hostname(string)
返回值:ip(string) 
功能: 通过端口名获取对应服务名
方法: getservbyport()
参数: port(int)
返回值:ip(string)


........

#!/usr/bin/env python
#coding:utf-8
'''
An example of getting some information of the host
'''
import socket

#获取设备名称
def gethostName():
    return socket.gethostname()

#获取设备ipv4地址
def gethostIp(host_name):
    return socket.gethostbyname(host_name)

#通过端口名获取对应服务名
def getServiceName(port):
    return socket.getservbyport(port)


#把ipv4转换为打包后的32位二进制格式并用十六进制表示
from binascii import hexlify
def convert_ipv4_to_hex(ipv4):
    ip_binary = socket.inet_aton(ipv4)
    return hexlify(ip_binary)

#将数据转化为网络字节序
def convert_data_to_networkEndian(data):
    return socket.htonl(data)



if __name__ == '__main__':
    print gethostName()
    print gethostIp("www.baidu.com")
    print convert_ipv4_to_hex('127.0.0.1')
    print getServiceName(21)
    print convert_data_to_networkEndian(1234)
    print convert_data_to_hostEndian(1234)

执行结果:

字节序转换补充: 

"""
字节序/主机序转换方法:

  htons 把 unsigned short 类型从主机序转换到网络序
  htonl 把 unsigned long 类型从主机序转换到网络序
  ntohs 把 unsigned short 类型从网络序转换到主机序
  ntohl 把 unsigned long 类型从网络序转换到主机序
"""

 可以使用help查看方法的属性

socket中一些常用方法:

原文地址:https://www.cnblogs.com/ssooking/p/5810959.html