获取设备名称和IPv4地址
socket.gethostname()
socket.gethostbyname(host_name)
1 def print_machine_info(): 2 host_name = socket.gethostname(); 3 ip_address = socket.gethostbyname(host_name) 4 print ('host_name : ',host_name) 5 print (host_name,'\'IP : ',ip_address)
获取远程设备的IP地址
socket.gethostbyname(remote_host)
1 def get_remote_machine_info(remote_host): 2 try: 3 ip_address = socket.gethostbyname(remote_host) 4 print (remote_host,'\'IP : ',ip_address) 5 except (socket.error) as err_msg: 6 print (remote_host,err_msg)
通过指定的端口和协议找到服务名
socket.getservbyport(port)
1 def find_service_name(): 2 for port in [80,25,53,22]: 3 service = socket.getservbyport(port) 4 print (service)
设定并获取默认的套接字超时时间
s.gettimeout()
s.settimeout(n)
1 def test_socket_timeout(): 2 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 3 print (s.gettimeout()) 4 s.settimeout(20) 5 print (s.gettimeout()) 6
这种操作在开发服务器应用时很有用,若把超时时间设置为None,则禁用了套接字操作的超时检测
附上一张常用端口图 常用计算机端口
inet_aton inet_ntoa | 将IPv4地址转换成不同的格式(32位二进制) |
ntohl() htonl() | 主机字节序和网络字节序之间的相互转换 n(network),l(long),s(short) |