@@ -1019,38 +1019,43 @@ async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
10191019 family , type_ , proto , _ , address = addr_info
10201020 sock = None
10211021 try :
1022- sock = socket .socket (family = family , type = type_ , proto = proto )
1023- sock .setblocking (False )
1024- if local_addr_infos is not None :
1025- for lfamily , _ , _ , _ , laddr in local_addr_infos :
1026- # skip local addresses of different family
1027- if lfamily != family :
1028- continue
1029- try :
1030- sock .bind (laddr )
1031- break
1032- except OSError as exc :
1033- msg = (
1034- f'error while attempting to bind on '
1035- f'address { laddr !r} : { str (exc ).lower ()} '
1036- )
1037- exc = OSError (exc .errno , msg )
1038- my_exceptions .append (exc )
1039- else : # all bind attempts failed
1040- if my_exceptions :
1041- raise my_exceptions .pop ()
1042- else :
1043- raise OSError (f"no matching local address with { family = } found" )
1044- await self .sock_connect (sock , address )
1045- return sock
1046- except OSError as exc :
1047- my_exceptions .append (exc )
1048- if sock is not None :
1049- sock .close ()
1050- raise
1022+ try :
1023+ sock = socket .socket (family = family , type = type_ , proto = proto )
1024+ sock .setblocking (False )
1025+ if local_addr_infos is not None :
1026+ for lfamily , _ , _ , _ , laddr in local_addr_infos :
1027+ # skip local addresses of different family
1028+ if lfamily != family :
1029+ continue
1030+ try :
1031+ sock .bind (laddr )
1032+ break
1033+ except OSError as exc :
1034+ msg = (
1035+ f'error while attempting to bind on '
1036+ f'address { laddr !r} : { str (exc ).lower ()} '
1037+ )
1038+ exc = OSError (exc .errno , msg )
1039+ my_exceptions .append (exc )
1040+ else : # all bind attempts failed
1041+ if my_exceptions :
1042+ raise my_exceptions .pop ()
1043+ else :
1044+ raise OSError (f"no matching local address with { family = } found" )
1045+ await self .sock_connect (sock , address )
1046+ return sock
1047+ except OSError as exc :
1048+ my_exceptions .append (exc )
1049+ raise
10511050 except :
10521051 if sock is not None :
1053- sock .close ()
1052+ try :
1053+ sock .close ()
1054+ except OSError :
1055+ # An error when closing a newly created socket is
1056+ # not important, but it can overwrite more important
1057+ # non-OSError error. So ignore it.
1058+ pass
10541059 raise
10551060 finally :
10561061 exceptions = my_exceptions = None
0 commit comments