Imported Upstream version 12.1.0
[contrib/python-twisted.git] / twisted / internet / iocpreactor / iocpsupport / connectex.pxi
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4
5 def connect(long s, object addr, object obj):
6     """
7     CAUTION: unlike system ConnectEx(), this function returns 0 on success
8     """
9     cdef int family, rc
10     cdef myOVERLAPPED *ov
11     cdef sockaddr_in ipv4_name
12     cdef sockaddr_in6 ipv6_name
13     cdef sockaddr *name
14     cdef int namelen
15
16     if not have_connectex:
17         raise ValueError, 'ConnectEx is not available on this system'
18
19     family = getAddrFamily(s)
20     if family == AF_INET:
21         name = <sockaddr *>&ipv4_name
22         namelen = sizeof(ipv4_name)
23         fillinetaddr(&ipv4_name, addr)
24     elif family == AF_INET6:
25         name = <sockaddr *>&ipv6_name
26         namelen = sizeof(ipv6_name)
27         fillinet6addr(&ipv6_name, addr)
28     else:
29         raise ValueError, 'unsupported address family'
30     name.sa_family = family
31
32     ov = makeOV()
33     if obj is not None:
34         ov.obj = <PyObject *>obj
35
36     rc = lpConnectEx(s, name, namelen, NULL, 0, NULL, <OVERLAPPED *>ov)
37
38     if not rc:
39         rc = WSAGetLastError()
40         if rc != ERROR_IO_PENDING:
41             PyMem_Free(ov)
42             return rc
43
44     # operation is in progress
45     Py_XINCREF(obj)
46     return 0
47