使用socket进行进程间通信或者跨网络的计算机间通讯,有点类似日常生活中的发送快递。
根据发送方的需要,选择不同的物流公司:
在选择适合的公司和运输方式后,需要在app上做出选择,并根据要求填写一些信息。app会根据填写的信息,判断和提示是否可行。
比如,有液体的物品是不可以走空运的;
比如,当日达的物品是不能做到隐去发送方地址的;
比如,运送的物品重量大于3公斤,需要额外收取费用的;
比如,发送方不在同一个城市,当日达可能就无法使用。
发送双方的位置、以及寄送物品的某些性质,决定了可能选择的运送公司、运送方式、时限以及费用等。
socket编程也是如此。
发送方需要先确定一些参数,还要知道接受方的一些参数,然后选择合适的协议等内容。
好在 python socket 提供了一些可以直接使用的方法,方便使用者通过简单的方法调用,获得发送方需要使用的一些数据。
方法列举
- def close(integer):
close(integer) -> NoneClose 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.
- def dup(integer):
dup(integer) -> integerDuplicate 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.
- 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.
参考网址: https://www.man7.org/linux/man-pages/man3/getaddrinfo.3.html
- def getdefaulttimeout():
getdefaulttimeout() -> timeoutReturns 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.
- 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.
- def gethostbyname(host):
gethostbyname(host) -> addressReturn the IP address (a string of the form '255.255.255.255') for a host.
- 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.
- def gethostname():
gethostname() -> stringReturn the current host name.
- def getnameinfo(sockaddr, flags):
getnameinfo(sockaddr, flags) --> (host, port)Get host and port for a sockaddr.
- def getprotobyname(name):
getprotobyname(name) -> integerReturn the protocol number for the named protocol. (Rarely used.)
- def getservbyname(servicename, protocolname=None):
getservbyname(servicename[, protocolname]) -> integerReturn 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.
- def getservbyport(port, protocolname=None):
getservbyport(port[, protocolname]) -> stringReturn 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.
- def htonl(integer):
htonl(integer) -> integerConvert a 32-bit integer from host to network byte order.
- def htons(integer):
htons(integer) -> integerConvert 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.
- def if_indextoname(if_index):
if_indextoname(if_index)Returns the interface name corresponding to the interface index if_index.
- def if_nameindex():
if_nameindex()Returns a list of network interface information (index, name) tuples.
- def if_nametoindex(if_name):
if_nametoindex(if_name)Returns the interface index corresponding to the interface name if_name.
- def inet_aton(string):
inet_aton(string) -> bytes giving packed 32-bit IP representationConvert an IP address in string format (123.45.67.89) to the 32-bit packed binary format usedin low-level network functions.
- def inet_ntoa(packed_ip):
inet_ntoa(packed_ip) -> ip_address_stringConvert an IP address from 32-bit packed binary format to string format
- def inet_ntop(af, packed_ip):
inet_ntop(af, packed_ip) -> string formatted IP addressConvert a packed IP address of the given family to string format.
- def inet_pton(af, ip):
inet_pton(af, ip) -> packed IP address stringConvert an IP address from string format to a packed string suitable for use with low-level network functions.
- def ntohl(integer):
ntohl(integer) -> integerConvert a 32-bit integer from network to host byte order.
- def ntohs(integer):
ntohs(integer) -> integerConvert 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.
- 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.
代码举例
- 获得本地主机信息
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)
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))
IP address: 72.14.178.174
- 输出默认超时时间
def print_default_timeout():print("Default timeout :", socket.getdefaulttimeout())
Default timeout : None
- 根据网址获得主机名、别名列表、IP列表
def print_host_by_addr():print("Host address :", socket.gethostbyaddr('www.pythons.org'))
Host address : (‘li40-174.members.linode.com’, [], [‘72.14.178.174’])
- 输出本地主机网卡信息
def print_network_interface():print(socket.if_nameindex())
[(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))
ethernet_0
- 根据域名获取远程主机IP
def get_remote_hostbyname():print(socket.gethostbyname('www.pythons.org'))
45.33.18.44
- 根据域名获取远程主机更多信息,返回主机域名、别名列表和IP列表
def get_remote_hostbyname_ex():print(socket.gethostbyname_ex('www.pythons.org'))
(‘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)
[(<AddressFamily.AF_INET: 2>, 0, 6, ‘’, (‘45.33.18.44’, 80)), (<AddressFamily.AF_INET: 2>, 0, 6, ‘’, (‘96.126.123.244’, 80)), (<AddressFamily.AF_INET: 2>, 0, 6, ‘’, (‘45.33.23.183’, 80)), (<AddressFamily.AF_INET: 2>, 0, 6, ‘’, (‘45.33.2.79’, 80)), (<AddressFamily.AF_INET: 2>, 0, 6, ‘’, (‘173.255.194.134’, 80)), (<AddressFamily.AF_INET: 2>, 0, 6, ‘’, (‘45.33.30.197’, 80)), (<AddressFamily.AF_INET: 2>, 0, 6, ‘’, (‘45.79.19.196’, 80)), (<AddressFamily.AF_INET: 2>, 0, 6, ‘’, (‘45.33.20.235’, 80)), (<AddressFamily.AF_INET: 2>, 0, 6, ‘’, (‘72.14.185.43’, 80)), (<AddressFamily.AF_INET: 2>, 0, 6, ‘’, (‘45.56.79.23’, 80)), (<AddressFamily.AF_INET: 2>, 0, 6, ‘’, (‘198.58.118.167’, 80)), (<AddressFamily.AF_INET: 2>, 0, 6, ‘’, (‘72.14.178.174’, 80))]
- 参考网址:
https://docs.python.org/3/library/socket.html