1from _pydevd_bundle import pydevd_constants 2from _pydev_imps._pydev_saved_modules import socket 3import sys 4 5IS_JYTHON = sys.platform.find('java') != -1 6 7_cache = None 8def get_localhost(): 9 ''' 10 Should return 127.0.0.1 in ipv4 and ::1 in ipv6 11 12 localhost is not used because on windows vista/windows 7, there can be issues where the resolving doesn't work 13 properly and takes a lot of time (had this issue on the pyunit server). 14 15 Using the IP directly solves the problem. 16 ''' 17 # TODO: Needs better investigation! 18 19 global _cache 20 if _cache is None: 21 try: 22 for addr_info in socket.getaddrinfo("localhost", 80, 0, 0, socket.SOL_TCP): 23 config = addr_info[4] 24 if config[0] == '127.0.0.1': 25 _cache = '127.0.0.1' 26 return _cache 27 except: 28 # Ok, some versions of Python don't have getaddrinfo or SOL_TCP... Just consider it 127.0.0.1 in this case. 29 _cache = '127.0.0.1' 30 else: 31 _cache = 'localhost' 32 33 return _cache 34 35 36def get_socket_names(n_sockets, close=False): 37 socket_names = [] 38 sockets = [] 39 for _ in range(n_sockets): 40 if IS_JYTHON: 41 # Although the option which would be pure java *should* work for Jython, the socket being returned is still 0 42 # (i.e.: it doesn't give the local port bound, only the original port, which was 0). 43 from java.net import ServerSocket 44 sock = ServerSocket(0) 45 socket_name = get_localhost(), sock.getLocalPort() 46 else: 47 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 48 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 49 sock.bind((get_localhost(), 0)) 50 socket_name = sock.getsockname() 51 52 sockets.append(sock) 53 socket_names.append(socket_name) 54 55 if close: 56 for s in sockets: 57 s.close() 58 return socket_names 59 60def get_socket_name(close=False): 61 return get_socket_names(1, close)[0] 62 63if __name__ == '__main__': 64 print(get_socket_name())