• python socket编程2 - socket创建发送方所需参数的获得


    使用socket进行进程间通信或者跨网络的计算机间通讯,有点类似日常生活中的发送快递。

    根据发送方的需要,选择不同的物流公司:
    在这里插入图片描述
    在选择适合的公司和运输方式后,需要在app上做出选择,并根据要求填写一些信息。app会根据填写的信息,判断和提示是否可行。

    比如,有液体的物品是不可以走空运的;
    比如,当日达的物品是不能做到隐去发送方地址的;
    比如,运送的物品重量大于3公斤,需要额外收取费用的;
    比如,发送方不在同一个城市,当日达可能就无法使用。

    发送双方的位置、以及寄送物品的某些性质,决定了可能选择的运送公司、运送方式、时限以及费用等。

    socket编程也是如此。

    发送方需要先确定一些参数,还要知道接受方的一些参数,然后选择合适的协议等内容。

    好在 python socket 提供了一些可以直接使用的方法,方便使用者通过简单的方法调用,获得发送方需要使用的一些数据。

    方法列举

    • def close(integer):
        close(integer) -> None
        
        Close an integer socket file descriptor.  
        This is like os.close(), but for sockets; 
        on some platforms os.close() won't work for socket file descriptors.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • def dup(integer):
        dup(integer) -> integer
        
        Duplicate an integer socket file descriptor.  This is like os.dup(), but for  sockets; 
        on some platforms os.dup() won't work for socket file descriptors.
    
    • 1
    • 2
    • 3
    • 4
    • def getaddrinfo(host, port, family=None, type=None, proto=None, flags=None):
       getaddrinfo(host, port [, family, type, proto, flags])   -> list of (family, type, proto, canonname, sockaddr)
        
        Resolve host and port into addrinfo struct.
    
    • 1
    • 2
    • 3

    参考网址: https://www.man7.org/linux/man-pages/man3/getaddrinfo.3.html

    • def getdefaulttimeout():
        getdefaulttimeout() -> timeout
        
        Returns the default timeout in seconds (float) for new socket objects.
        A value of None indicates that new socket objects have no timeout.
        When the socket module is first imported, the default is None.
        默认是None.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • def gethostbyaddr(host):
        gethostbyaddr(host) -> (name, aliaslist, addresslist)
        
        Return the true host name, a list of aliases, and a list of IP addresses, for a host.  
        The host argument is a string giving a host name or IP number.
    
    • 1
    • 2
    • 3
    • 4
    • def gethostbyname(host):
        gethostbyname(host) -> address
        
        Return the IP address (a string of the form '255.255.255.255') for a host.
    
    • 1
    • 2
    • 3
    • def gethostbyname_ex(host):
        gethostbyname_ex(host) -> (name, aliaslist, addresslist)
        
        Return the true host name, a list of aliases, and a list of IP addresses, for a host.  
        The host argument is a string giving a host name or IP number.
    
    • 1
    • 2
    • 3
    • 4
    • def gethostname():
        gethostname() -> string
        
        Return the current host name.
    
    • 1
    • 2
    • 3
    • def getnameinfo(sockaddr, flags):
        getnameinfo(sockaddr, flags) --> (host, port)
        
        Get host and port for a sockaddr.
    
    • 1
    • 2
    • 3
    • def getprotobyname(name):
        getprotobyname(name) -> integer
        
        Return the protocol number for the named protocol.  (Rarely used.)
    
    • 1
    • 2
    • 3
    • def getservbyname(servicename, protocolname=None):
        getservbyname(servicename[, protocolname]) -> integer
        
        Return a port number from a service name and protocol name.
        The optional protocol name, if given, should be 'tcp' or 'udp',   otherwise any protocol will match.
    
    • 1
    • 2
    • 3
    • 4
    • def getservbyport(port, protocolname=None):
        getservbyport(port[, protocolname]) -> string
        
        Return the service name from a port number and protocol name.
        The optional protocol name, if given, should be 'tcp' or 'udp', otherwise any protocol will match.
    
    • 1
    • 2
    • 3
    • 4
    • def htonl(integer):
        htonl(integer) -> integer
        
        Convert a 32-bit integer from host to network byte order.
    
    • 1
    • 2
    • 3
    • def htons(integer):
        htons(integer) -> integer
        
        Convert a 16-bit unsigned integer from host to network byte order.
        Note that in case the received integer does not fit in 16-bit unsigned integer, 
        but does fit in a positive C int, it is silently truncated to 16-bit unsigned integer.
        However, this silent truncation feature is deprecated, and will raise an  exception in future versions of Python.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • def if_indextoname(if_index):
        if_indextoname(if_index)
        
        Returns the interface name corresponding to the interface index if_index.
    
    • 1
    • 2
    • 3
    • def if_nameindex():
        if_nameindex()
        
        Returns a list of network interface information (index, name) tuples.
    
    • 1
    • 2
    • 3
    • def if_nametoindex(if_name):
        if_nametoindex(if_name)
        
        Returns the interface index corresponding to the interface name if_name.
    
    • 1
    • 2
    • 3
    • def inet_aton(string):
        inet_aton(string) -> bytes giving packed 32-bit IP representation
        
        Convert an IP address in string format (123.45.67.89) to the 32-bit packed  binary format used
        in low-level network functions.
    
    • 1
    • 2
    • 3
    • 4
    • def inet_ntoa(packed_ip):
        inet_ntoa(packed_ip) -> ip_address_string
        
        Convert an IP address from 32-bit packed binary format to string format
    
    • 1
    • 2
    • 3
    • def inet_ntop(af, packed_ip):
        inet_ntop(af, packed_ip) -> string formatted IP address
        
        Convert a packed IP address of the given family to string format.
    
    • 1
    • 2
    • 3
    • def inet_pton(af, ip):
        inet_pton(af, ip) -> packed IP address string
        
        Convert an IP address from string format to a packed string suitable  for use with low-level network functions.
    
    • 1
    • 2
    • 3
    • def ntohl(integer):
        ntohl(integer) -> integer
        
        Convert a 32-bit integer from network to host byte order.
    
    • 1
    • 2
    • 3
    • def ntohs(integer):
        ntohs(integer) -> integer
        
        Convert a 16-bit unsigned integer from network to host byte order.
        Note that in case the received integer does not fit in 16-bit unsigned  integer, but does fit in a positive C int,
         it is silently truncated to  16-bit unsigned integer.
        However, this silent truncation feature is deprecated, and will raise an  exception in future versions of Python.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • def setdefaulttimeout(timeout):
        setdefaulttimeout(timeout)
        
        Set the default timeout in seconds (float) for new socket objects.
        A value of None indicates that new socket objects have no timeout.
        When the socket module is first imported, the default is None.
    
    • 1
    • 2
    • 3
    • 4
    • 5

    代码举例

    • 获得本地主机信息
    def print_localhost_info():
        host_name = socket.gethostname()
        ip_addr = socket.gethostbyname(host_name)
        print("Host name: %s " % host_name)
        print("IP address: %s" % ip_addr)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Host name: DESKTOP-DEVTEAM
    IP address: 192.168.56.1

    • 获得外网站点信息
    def print_remote_website_info():
        remote_host = 'www.pythons.org'
        try:
            print("IP address: %s" % socket.gethostbyname(remote_host))
        except socket.error as err_msg:
            print("%s: %s" % (remote_host, err_msg))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    IP address: 72.14.178.174

    • 输出默认超时时间
    def print_default_timeout():
        print("Default timeout :", socket.getdefaulttimeout())
    
    • 1
    • 2

    Default timeout : None

    • 根据网址获得主机名、别名列表、IP列表
    def print_host_by_addr():
        print("Host address :", socket.gethostbyaddr('www.pythons.org'))
    
    • 1
    • 2

    Host address : (‘li40-174.members.linode.com’, [], [‘72.14.178.174’])

    • 输出本地主机网卡信息
    def print_network_interface():
        print(socket.if_nameindex())
    
    • 1
    • 2

    [(22, ‘ethernet_0’), (23, ‘ethernet_1’), (24, ‘ethernet_2’), (25, ‘ethernet_3’), (26, ‘ethernet_4’), (27, ‘ethernet_5’), (28, ‘ethernet_6’), (29, ‘ethernet_7’), (30, ‘ethernet_8’), (31, ‘ethernet_9’), (32, ‘ethernet_10’), (33, ‘ethernet_11’), (43, ‘ethernet_12’), (44, ‘ethernet_13’), (45, ‘ethernet_14’), (46, ‘ethernet_15’), (47, ‘ethernet_16’), (48, ‘ethernet_17’), (49, ‘ethernet_18’), (50, ‘ethernet_19’), (51, ‘ethernet_20’), (12, ‘ethernet_32768’), (15, ‘ethernet_32769’), (2, ‘ethernet_32770’), (9, ‘ethernet_32771’), (21, ‘ethernet_32772’), (7, ‘ethernet_32773’), (14, ‘ethernet_32774’), (20, ‘ethernet_32775’), (6, ‘ethernet_32776’), (8, ‘ppp_32768’), (1, ‘loopback_0’), (34, ‘wireless_0’), (35, ‘wireless_1’), (36, ‘wireless_2’), (37, ‘wireless_3’), (38, ‘wireless_4’), (39, ‘wireless_5’), (40, ‘wireless_6’), (41, ‘wireless_7’), (42, ‘wireless_8’), (52, ‘wireless_9’), (53, ‘wireless_10’), (54, ‘wireless_11’), (55, ‘wireless_12’), (56, ‘wireless_13’), (57, ‘wireless_14’), (58, ‘wireless_15’), (59, ‘wireless_16’), (60, ‘wireless_17’), (61, ‘wireless_18’), (18, ‘wireless_32768’), (19, ‘wireless_32769’), (11, ‘wireless_32770’), (13, ‘tunnel_32512’), (5, ‘tunnel_32513’), (3, ‘tunnel_32514’), (16, ‘tunnel_32768’), (4, ‘tunnel_32769’), (17, ‘tunnel_32770’), (10, ‘tunnel_32771’)]

    • 根据网络接口的索引获取名字
    def print_network_interface_name():
        print(socket.if_indextoname(22))
    
    • 1
    • 2

    ethernet_0

    • 根据域名获取远程主机IP
    def get_remote_hostbyname():
        print(socket.gethostbyname('www.pythons.org'))
    
    • 1
    • 2

    45.33.18.44

    • 根据域名获取远程主机更多信息,返回主机域名、别名列表和IP列表
    def get_remote_hostbyname_ex():
        print(socket.gethostbyname_ex('www.pythons.org'))
    
    • 1
    • 2

    (‘www.pythons.org’, [], [‘45.33.18.44’, ‘96.126.123.244’, ‘45.33.23.183’, ‘45.33.2.79’, ‘173.255.194.134’, ‘45.33.30.197’, ‘45.79.19.196’, ‘45.33.20.235’, ‘72.14.185.43’, ‘45.56.79.23’, ‘198.58.118.167’, ‘72.14.178.174’])

    • 获取远程主机信息
    def getaddrinfo():
        info = socket.getaddrinfo("www.pythons.org", 80, proto=socket.IPPROTO_TCP)
        print(info)
    
    • 1
    • 2
    • 3

    [(, 0, 6, ‘’, (‘45.33.18.44’, 80)), (, 0, 6, ‘’, (‘96.126.123.244’, 80)), (, 0, 6, ‘’, (‘45.33.23.183’, 80)), (, 0, 6, ‘’, (‘45.33.2.79’, 80)), (, 0, 6, ‘’, (‘173.255.194.134’, 80)), (, 0, 6, ‘’, (‘45.33.30.197’, 80)), (, 0, 6, ‘’, (‘45.79.19.196’, 80)), (, 0, 6, ‘’, (‘45.33.20.235’, 80)), (, 0, 6, ‘’, (‘72.14.185.43’, 80)), (, 0, 6, ‘’, (‘45.56.79.23’, 80)), (, 0, 6, ‘’, (‘198.58.118.167’, 80)), (, 0, 6, ‘’, (‘72.14.178.174’, 80))]

    • 参考网址:
      https://docs.python.org/3/library/socket.html
  • 相关阅读:
    2022世界人工智能大会 “智慧金融与数字员工”分论坛在沪成功举办
    2022高处安装、维护、拆除考试练习题及答案
    OpenGV
    sql-lib 搭建&31-40关
    Spring MVC组件之HandlerAdapter
    Tomcat
    USB转串口芯片CH340系列及CH340模块使用方法(CH340驱动,接线,串口下载详细介绍)
    网络原理---网络初识
    1. Java并发编程-开篇
    数据利器:营销人员的智能助手,助力精准营销,实现业务增长
  • 原文地址:https://blog.csdn.net/teamlet/article/details/134408318