@@ -110,19 +110,29 @@ def _connect(self, fam, typ):
110
110
sock = None
111
111
timeout = self .timeout
112
112
113
- async def resolve_hostname (host , port , fam = 0 , typ = 0 , proto = 0 , flags = 0 ):
114
- loop = asyncio .get_event_loop ()
113
+ async def async_getaddrinfo (host , port , fam = 0 , typ = 0 , proto = 0 , flags = 0 ):
114
+ loop = asyncio .get_running_loop ()
115
115
try :
116
116
result = await loop .getaddrinfo (host , port , family = fam , type = typ , proto = proto , flags = flags )
117
117
except asyncio .exceptions .CancelledError :
118
118
result = []
119
119
return result
120
120
121
+ # Using asyncio to avoid blocking when DNS resolution fail. It's probably better
122
+ # to use async all the ways to `sock.connect`. However, let's keep the changes
123
+ # small until we have the needs.
124
+ def sync_getaddrinfo (* info_args ):
125
+ loop = asyncio .get_event_loop ()
126
+ if loop .is_running ():
127
+ # If an event loop is already running, use it to run the async function
128
+ future = asyncio .run_coroutine_threadsafe (async_getaddrinfo (* info_args ), loop )
129
+ return future .result ()
130
+ else :
131
+ # If no event loop is running, create a new one
132
+ return asyncio .run (async_getaddrinfo (* info_args ))
133
+
121
134
with self .waitfor ('Opening connection to %s on port %s' % (self .rhost , self .rport )) as h :
122
- # Using asyncio to avoid blocking when DNS resolution fail. It's probably better
123
- # to use async all the ways to `sock.connect`. However, let's keep the changes
124
- # small until we have the needs.
125
- hostnames = asyncio .run (resolve_hostname (self .rhost , self .rport , fam , typ , 0 , socket .AI_PASSIVE ))
135
+ hostnames = sync_getaddrinfo (self .rhost , self .rport , fam , typ , 0 , socket .AI_PASSIVE )
126
136
for res in hostnames :
127
137
self .family , self .type , self .proto , _canonname , sockaddr = res
128
138
0 commit comments