Coverage for mfutil/net.py: 72%

85 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-12-18 16:04 +0000

1"""Utility functions around network.""" 

2 

3import logging 

4import socket 

5import netifaces 

6 

7 

8def __get_logger(): 

9 return logging.getLogger("mfutil.net") 

10 

11 

12def get_ip_for_hostname(hostname, ignore_hostnames_list=["AUTO"]): 

13 """Get the IP of a given hostname. 

14 

15 Args: 

16 hostname (string): hostname to find. 

17 ignore_hostnames_list (list of strings): special hostname values which 

18 won't be lookup ip (if the given hostname is in this list, this 

19 function will return the given hostname without any modification). 

20 Returns: 

21 (string) IP of the given hostname (or None if we can't find it). 

22 

23 """ 

24 if hostname in ignore_hostnames_list: 

25 return hostname 

26 if hostname in ("127.0.0.1", "localhost", "localhost.localdomain"): 

27 return "127.0.0.1" 

28 try: 

29 infos = socket.getaddrinfo(hostname, 80, 0, 0, socket.IPPROTO_TCP) 

30 except Exception: 

31 return None 

32 for (family, sockettype, proto, canonname, sockaddr) in infos: 

33 if sockaddr is None or len(sockaddr) != 2: 

34 continue 

35 tmp = sockaddr[0] 

36 if '.' not in tmp: 

37 # we don't want ipv6 

38 continue 

39 return tmp 

40 return None 

41 

42 

43def get_simple_hostname(): 

44 """Return the "simple" hostname of the server. 

45 

46 "simple" hostname means "without network domain", so without any dot 

47 in the hostname. 

48 

49 Returns: 

50 string: the "simple" hostname of the server. 

51 

52 """ 

53 return socket.gethostname().split('.')[0] 

54 

55 

56def _get_domainname_from_resolv_conf(resolv_conf_file="/etc/resolv.conf"): 

57 with open(resolv_conf_file, "r") as f: 

58 lines = f.readlines() 

59 for line in lines: 

60 tmp = line.strip() 

61 if tmp.startswith("domain"): 

62 cols = tmp.split() 

63 if len(cols) >= 2: 

64 return cols[1] 

65 return None 

66 

67 

68def get_domainname(use_resolv_conf=True, resolv_conf_file="/etc/resolv.conf"): 

69 """Get the domain name of the server. 

70 

71 The domain name does not include the hostname. 

72 

73 We try first with the getfqdn method then with the resolv.conf file because 

74 the domain can be found here. 

75 

76 Args: 

77 use_resolv_conf (boolean): if set to True, we use the resolv.conf file. 

78 resolv_conf_file (string): full path of the resolv.conf file (useful 

79 for unit testing). 

80 

81 Returns: 

82 string: the domain name of the server (or None if we can't find it) 

83 

84 """ 

85 tmp = socket.getfqdn(get_simple_hostname()) 

86 if '.' in tmp: 

87 return ".".join(tmp.split('.')[1:]) 

88 if use_resolv_conf: 

89 return _get_domainname_from_resolv_conf(resolv_conf_file) 

90 return None 

91 

92 

93def get_full_hostname(use_resolv_conf=True, 

94 resolv_conf_file="/etc/resolv.conf"): 

95 """Return the "full" hostname of the server. 

96 

97 "full" hostname means "with network domain" appended. 

98 

99 Args: 

100 use_resolv_conf (boolean): if set to True, we use the resolv.conf file 

101 to find the domain name. 

102 resolv_conf_file (string): full path of the resolv.conf file (useful 

103 for unit testing). 

104 

105 Returns: 

106 string: the "full" hostname of the server. 

107 

108 """ 

109 tmp = socket.getfqdn(get_simple_hostname()) 

110 if '.' in tmp or not use_resolv_conf: 

111 return tmp 

112 domainname = get_domainname(use_resolv_conf, resolv_conf_file) 

113 if domainname is not None: 

114 return "%s.%s" % (get_simple_hostname(), domainname) 

115 return get_simple_hostname() 

116 

117 

118def _get_real_ip_netifaces(): 

119 # pylint: disable=E1101 

120 ip = "127.0.0.1" 

121 try: 

122 # we try first with the default gateway 

123 def_gw_device = netifaces.gateways()['default'][netifaces.AF_INET][1] 

124 infos = netifaces.ifaddresses(def_gw_device) 

125 ip = str(infos[netifaces.AF_INET][0]['addr']) 

126 except Exception: 

127 pass 

128 if ip != "127.0.0.1": 

129 return ip 

130 # we try every interface 

131 for interface in netifaces.interfaces(): 

132 try: 

133 infos = netifaces.ifaddresses(interface) 

134 ip = str(infos[netifaces.AF_INET][0]['addr']) 

135 except Exception: 

136 pass 

137 if ip != "127.0.0.1": 

138 return ip 

139 return ip 

140 

141 

142def get_real_ip(): 

143 """Try to find and return the real IP of the server. 

144 

145 We try to avoid to return 127.0.0.1 by examining network interfaces. 

146 

147 Returns: 

148 string: the real IP of the server. 

149 

150 """ 

151 hostname = get_simple_hostname() 

152 ip = get_ip_for_hostname(hostname) 

153 if ip != "127.0.0.1": 

154 return ip 

155 # try to find the real ip (not 127.0.0.1) 

156 return _get_real_ip_netifaces() 

157 

158 

159def ping_tcp_port(host, port, timeout=5): 

160 """Ping a TCP host/port with a configurable timeout. 

161 

162 It's not really a ping but a little connection attempt to see if the 

163 port is open and listened. The timeout is useful when there is a kind 

164 of firewall between. 

165 

166 No Exception are raised in any case. 

167 

168 Args: 

169 host (string): the hostname/ip to ping. 

170 port (int): the TCP port to ping. 

171 timeout (int): timeout in seconds. 

172 

173 Returns: 

174 boolean: True if the port is open and listened. 

175 

176 """ 

177 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

178 sock.settimeout(timeout) 

179 try: 

180 result = sock.connect_ex((host, port)) 

181 if result == 0: 

182 sock.close() 

183 return True 

184 except Exception: 

185 pass 

186 return False