Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Modules/socketmodule.c

    r2 r388  
    1818- socket.error: exception raised for socket specific errors
    1919- socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
    20         a subclass of socket.error
     20    a subclass of socket.error
    2121- socket.herror: exception raised for gethostby* errors,
    22         a subclass of socket.error
     22    a subclass of socket.error
    2323- socket.fromfd(fd, family, type[, proto]) --> new socket object (created
    24         from an existing file descriptor)
     24    from an existing file descriptor)
    2525- socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
    2626- socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
     
    3636- socket.htonl(32 bit value) --> new int object
    3737- socket.getaddrinfo(host, port [, family, socktype, proto, flags])
    38         --> List of (family, socktype, proto, canonname, sockaddr)
     38    --> List of (family, socktype, proto, canonname, sockaddr)
    3939- socket.getnameinfo(sockaddr, flags) --> (host, port)
    4040- socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
     
    5656- an AF_TIPC socket address is expressed as
    5757 (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
    58         TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
     58    TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
    5959  and scope can be one of:
    60         TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
     60    TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
    6161  The meaning of v1, v2 and v3 depends on the value of addr_type:
    62         if addr_type is TIPC_ADDR_NAME:
    63                 v1 is the server type
    64                 v2 is the port identifier
    65                 v3 is ignored
    66         if addr_type is TIPC_ADDR_NAMESEQ:
    67                 v1 is the server type
    68                 v2 is the lower port number
    69                 v3 is the upper port number
    70         if addr_type is TIPC_ADDR_ID:
    71                 v1 is the node
    72                 v2 is the ref
    73                 v3 is ignored
     62    if addr_type is TIPC_ADDR_NAME:
     63        v1 is the server type
     64        v2 is the port identifier
     65        v3 is ignored
     66    if addr_type is TIPC_ADDR_NAMESEQ:
     67        v1 is the server type
     68        v2 is the lower port number
     69        v3 is the upper port number
     70    if addr_type is TIPC_ADDR_ID:
     71        v1 is the node
     72        v2 is the ref
     73        v3 is ignored
    7474
    7575
     
    9393#include "Python.h"
    9494#include "structmember.h"
     95#include "timefuncs.h"
    9596
    9697#undef MAX
     
    296297
    297298#ifndef offsetof
    298 # define offsetof(type, member) ((size_t)(&((type *)0)->member))
     299# define offsetof(type, member) ((size_t)(&((type *)0)->member))
    299300#endif
    300301
     
    380381#endif
    381382
    382 #if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H) &&  !defined(__NetBSD__)
     383#if (defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)) && !defined(__NetBSD__) && !defined(__DragonFly__)
    383384#define USE_BLUETOOTH 1
    384385#if defined(__FreeBSD__)
     
    394395#define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
    395396#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
    396 #elif defined(__NetBSD__)
     397#elif defined(__NetBSD__) || defined(__DragonFly__)
    397398#define sockaddr_l2 sockaddr_bt
    398399#define sockaddr_rc sockaddr_bt
    399400#define sockaddr_hci sockaddr_bt
    400401#define sockaddr_sco sockaddr_bt
     402#define SOL_HCI BTPROTO_HCI
     403#define HCI_DATA_DIR SO_HCI_DIRECTION
    401404#define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
    402405#define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
     
    416419#endif
    417420
    418 #define SAS2SA(x)       ((struct sockaddr *)(x))
     421#define SAS2SA(x)       ((struct sockaddr *)(x))
    419422
    420423/*
     
    455458#endif
    456459
    457 #ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
    458 /* Platform can select file descriptors beyond FD_SETSIZE */
    459 #define IS_SELECTABLE(s) 1
    460 #elif defined(HAVE_POLL)
     460#ifdef HAVE_POLL
    461461/* Instead of select(), we'll use poll() since poll() works on any fd. */
    462462#define IS_SELECTABLE(s) 1
    463463/* Can we call select() with this socket without a buffer overrun? */
    464464#else
    465 /* POSIX says selecting file descriptors beyond FD_SETSIZE
    466    has undefined behaviour.  If there's no timeout left, we don't have to
    467    call select, so it's a safe, little white lie. */
    468 #define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
     465/* If there's no timeout left, we don't have to call select, so it's a safe,
     466 * little white lie. */
     467#define IS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0.0)
    469468#endif
    470469
     
    472471select_error(void)
    473472{
    474         PyErr_SetString(socket_error, "unable to select on socket");
    475         return NULL;
    476 }
     473    PyErr_SetString(socket_error, "unable to select on socket");
     474    return NULL;
     475}
     476
     477#ifdef MS_WINDOWS
     478#ifndef WSAEAGAIN
     479#define WSAEAGAIN WSAEWOULDBLOCK
     480#endif
     481#define CHECK_ERRNO(expected) \
     482    (WSAGetLastError() == WSA ## expected)
     483#else
     484#define CHECK_ERRNO(expected) \
     485    (errno == expected)
     486#endif
    477487
    478488/* Convenience function to raise an error according to errno
     
    483493{
    484494#ifdef MS_WINDOWS
    485         int err_no = WSAGetLastError();
    486         /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
    487            recognizes the error codes used by both GetLastError() and
    488            WSAGetLastError */
    489         if (err_no)
    490                 return PyErr_SetExcFromWindowsErr(socket_error, err_no);
     495    int err_no = WSAGetLastError();
     496    /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
     497       recognizes the error codes used by both GetLastError() and
     498       WSAGetLastError */
     499    if (err_no)
     500        return PyErr_SetExcFromWindowsErr(socket_error, err_no);
    491501#endif
    492502
    493503#if defined(PYOS_OS2) && !defined(PYCC_GCC)
    494         if (sock_errno() != NO_ERROR) {
    495                 APIRET rc;
    496                 ULONG  msglen;
    497                 char outbuf[100];
    498                 int myerrorcode = sock_errno();
    499 
    500                 /* Retrieve socket-related error message from MPTN.MSG file */
    501                 rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
    502                                    myerrorcode - SOCBASEERR + 26,
    503                                    "mptn.msg",
    504                                    &msglen);
    505                 if (rc == NO_ERROR) {
    506                         PyObject *v;
    507 
    508                         /* OS/2 doesn't guarantee a terminator */
    509                         outbuf[msglen] = '\0';
    510                         if (strlen(outbuf) > 0) {
    511                                 /* If non-empty msg, trim CRLF */
    512                                 char *lastc = &outbuf[ strlen(outbuf)-1 ];
    513                                 while (lastc > outbuf &&
    514                                        isspace(Py_CHARMASK(*lastc))) {
    515                                         /* Trim trailing whitespace (CRLF) */
    516                                         *lastc-- = '\0';
    517                                 }
    518                         }
    519                         v = Py_BuildValue("(is)", myerrorcode, outbuf);
    520                         if (v != NULL) {
    521                                 PyErr_SetObject(socket_error, v);
    522                                 Py_DECREF(v);
    523                         }
    524                         return NULL;
    525                 }
    526         }
     504    if (sock_errno() != NO_ERROR) {
     505        APIRET rc;
     506        ULONG  msglen;
     507        char outbuf[100];
     508        int myerrorcode = sock_errno();
     509
     510        /* Retrieve socket-related error message from MPTN.MSG file */
     511        rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
     512                           myerrorcode - SOCBASEERR + 26,
     513                           "mptn.msg",
     514                           &msglen);
     515        if (rc == NO_ERROR) {
     516            PyObject *v;
     517
     518            /* OS/2 doesn't guarantee a terminator */
     519            outbuf[msglen] = '\0';
     520            if (strlen(outbuf) > 0) {
     521                /* If non-empty msg, trim CRLF */
     522                char *lastc = &outbuf[ strlen(outbuf)-1 ];
     523                while (lastc > outbuf &&
     524                       isspace(Py_CHARMASK(*lastc))) {
     525                    /* Trim trailing whitespace (CRLF) */
     526                    *lastc-- = '\0';
     527                }
     528            }
     529            v = Py_BuildValue("(is)", myerrorcode, outbuf);
     530            if (v != NULL) {
     531                PyErr_SetObject(socket_error, v);
     532                Py_DECREF(v);
     533            }
     534            return NULL;
     535        }
     536    }
    527537#endif
    528538
    529539#if defined(RISCOS)
    530         if (_inet_error.errnum != NULL) {
    531                 PyObject *v;
    532                 v = Py_BuildValue("(is)", errno, _inet_err());
    533                 if (v != NULL) {
    534                         PyErr_SetObject(socket_error, v);
    535                         Py_DECREF(v);
    536                 }
    537                 return NULL;
    538         }
    539 #endif
    540 
    541         return PyErr_SetFromErrno(socket_error);
     540    if (_inet_error.errnum != NULL) {
     541        PyObject *v;
     542        v = Py_BuildValue("(is)", errno, _inet_err());
     543        if (v != NULL) {
     544            PyErr_SetObject(socket_error, v);
     545            Py_DECREF(v);
     546        }
     547        return NULL;
     548    }
     549#endif
     550
     551    return PyErr_SetFromErrno(socket_error);
    542552}
    543553
     
    546556set_herror(int h_error)
    547557{
    548         PyObject *v;
     558    PyObject *v;
    549559
    550560#ifdef HAVE_HSTRERROR
    551         v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
    552 #else
    553         v = Py_BuildValue("(is)", h_error, "host not found");
    554 #endif
    555         if (v != NULL) {
    556                 PyErr_SetObject(socket_herror, v);
    557                 Py_DECREF(v);
    558         }
    559 
    560         return NULL;
     561    v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
     562#else
     563    v = Py_BuildValue("(is)", h_error, "host not found");
     564#endif
     565    if (v != NULL) {
     566        PyErr_SetObject(socket_herror, v);
     567        Py_DECREF(v);
     568    }
     569
     570    return NULL;
    561571}
    562572
     
    565575set_gaierror(int error)
    566576{
    567         PyObject *v;
     577    PyObject *v;
    568578
    569579#ifdef EAI_SYSTEM
    570         /* EAI_SYSTEM is not available on Windows XP. */
    571         if (error == EAI_SYSTEM)
    572                 return set_error();
     580    /* EAI_SYSTEM is not available on Windows XP. */
     581    if (error == EAI_SYSTEM)
     582        return set_error();
    573583#endif
    574584
    575585#ifdef HAVE_GAI_STRERROR
    576         v = Py_BuildValue("(is)", error, gai_strerror(error));
    577 #else
    578         v = Py_BuildValue("(is)", error, "getaddrinfo failed");
    579 #endif
    580         if (v != NULL) {
    581                 PyErr_SetObject(socket_gaierror, v);
    582                 Py_DECREF(v);
    583         }
    584 
    585         return NULL;
     586    v = Py_BuildValue("(is)", error, gai_strerror(error));
     587#else
     588    v = Py_BuildValue("(is)", error, "getaddrinfo failed");
     589#endif
     590    if (v != NULL) {
     591        PyErr_SetObject(socket_gaierror, v);
     592        Py_DECREF(v);
     593    }
     594
     595    return NULL;
    586596}
    587597
     
    591601sendsegmented(int sock_fd, char *buf, int len, int flags)
    592602{
    593         int n = 0;
    594         int remaining = len;
    595 
    596         while (remaining > 0) {
    597                 unsigned int segment;
    598 
    599                 segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
    600                 n = send(sock_fd, buf, segment, flags);
    601                 if (n < 0) {
    602                         return n;
    603                 }
    604                 remaining -= segment;
    605                 buf += segment;
    606         } /* end while */
    607 
    608         return len;
     603    int n = 0;
     604    int remaining = len;
     605
     606    while (remaining > 0) {
     607        unsigned int segment;
     608
     609        segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
     610        n = send(sock_fd, buf, segment, flags);
     611        if (n < 0) {
     612            return n;
     613        }
     614        remaining -= segment;
     615        buf += segment;
     616    } /* end while */
     617
     618    return len;
    609619}
    610620#endif
     
    617627#ifndef RISCOS
    618628#ifndef MS_WINDOWS
    619         int delay_flag;
    620 #endif
    621 #endif
    622 
    623         Py_BEGIN_ALLOW_THREADS
     629    int delay_flag;
     630#endif
     631#endif
     632
     633    Py_BEGIN_ALLOW_THREADS
    624634#ifdef __BEOS__
    625         block = !block;
    626         setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
    627                    (void *)(&block), sizeof(int));
     635    block = !block;
     636    setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
     637               (void *)(&block), sizeof(int));
    628638#else
    629639#ifndef RISCOS
    630640#ifndef MS_WINDOWS
    631641#if defined(PYOS_OS2) && !defined(PYCC_GCC)
    632         block = !block;
    633         ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
     642    block = !block;
     643    ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
    634644#elif defined(__VMS)
    635         block = !block;
    636         ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
     645    block = !block;
     646    ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
    637647#else  /* !PYOS_OS2 && !__VMS */
    638         delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
    639         if (block)
    640                 delay_flag &= (~O_NONBLOCK);
    641         else
    642                 delay_flag |= O_NONBLOCK;
    643         fcntl(s->sock_fd, F_SETFL, delay_flag);
     648    delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
     649    if (block)
     650        delay_flag &= (~O_NONBLOCK);
     651    else
     652        delay_flag |= O_NONBLOCK;
     653    fcntl(s->sock_fd, F_SETFL, delay_flag);
    644654#endif /* !PYOS_OS2 */
    645655#else /* MS_WINDOWS */
    646         block = !block;
    647         ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
     656    block = !block;
     657    ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
    648658#endif /* MS_WINDOWS */
    649659#else /* RISCOS */
    650         block = !block;
    651         socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
     660    block = !block;
     661    socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
    652662#endif /* RISCOS */
    653663#endif /* __BEOS__ */
    654         Py_END_ALLOW_THREADS
    655 
    656         /* Since these don't return anything */
    657         return 1;
     664    Py_END_ALLOW_THREADS
     665
     666    /* Since these don't return anything */
     667    return 1;
    658668}
    659669
     
    664674   Returns 1 on timeout, -1 on error, 0 otherwise. */
    665675static int
     676internal_select_ex(PySocketSockObject *s, int writing, double interval)
     677{
     678    int n;
     679
     680    /* Nothing to do unless we're in timeout mode (not non-blocking) */
     681    if (s->sock_timeout <= 0.0)
     682        return 0;
     683
     684    /* Guard against closed socket */
     685    if (s->sock_fd < 0)
     686        return 0;
     687
     688    /* Handling this condition here simplifies the select loops */
     689    if (interval < 0.0)
     690        return 1;
     691
     692    /* Prefer poll, if available, since you can poll() any fd
     693     * which can't be done with select(). */
     694#ifdef HAVE_POLL
     695    {
     696        struct pollfd pollfd;
     697        int timeout;
     698
     699        pollfd.fd = s->sock_fd;
     700        pollfd.events = writing ? POLLOUT : POLLIN;
     701
     702        /* s->sock_timeout is in seconds, timeout in ms */
     703        timeout = (int)(interval * 1000 + 0.5);
     704        n = poll(&pollfd, 1, timeout);
     705    }
     706#else
     707    {
     708        /* Construct the arguments to select */
     709        fd_set fds;
     710        struct timeval tv;
     711        tv.tv_sec = (int)interval;
     712        tv.tv_usec = (int)((interval - tv.tv_sec) * 1e6);
     713        FD_ZERO(&fds);
     714        FD_SET(s->sock_fd, &fds);
     715
     716        /* See if the socket is ready */
     717        if (writing)
     718            n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
     719        else
     720            n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
     721    }
     722#endif
     723
     724    if (n < 0)
     725        return -1;
     726    if (n == 0)
     727        return 1;
     728    return 0;
     729}
     730
     731static int
    666732internal_select(PySocketSockObject *s, int writing)
    667733{
    668         int n;
    669 
    670         /* Nothing to do unless we're in timeout mode (not non-blocking) */
    671         if (s->sock_timeout <= 0.0)
    672                 return 0;
    673 
    674         /* Guard against closed socket */
    675         if (s->sock_fd < 0)
    676                 return 0;
    677 
    678         /* Prefer poll, if available, since you can poll() any fd
    679          * which can't be done with select(). */
    680 #ifdef HAVE_POLL
    681         {
    682                 struct pollfd pollfd;
    683                 int timeout;
    684 
    685                 pollfd.fd = s->sock_fd;
    686                 pollfd.events = writing ? POLLOUT : POLLIN;
    687 
    688                 /* s->sock_timeout is in seconds, timeout in ms */
    689                 timeout = (int)(s->sock_timeout * 1000 + 0.5);
    690                 n = poll(&pollfd, 1, timeout);
    691         }
    692 #else
    693         {
    694                 /* Construct the arguments to select */
    695                 fd_set fds;
    696                 struct timeval tv;
    697                 tv.tv_sec = (int)s->sock_timeout;
    698                 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
    699                 FD_ZERO(&fds);
    700                 FD_SET(s->sock_fd, &fds);
    701 
    702                 /* See if the socket is ready */
    703                 if (writing)
    704                         n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
    705                 else
    706                         n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
    707         }
    708 #endif
    709        
    710         if (n < 0)
    711                 return -1;
    712         if (n == 0)
    713                 return 1;
    714         return 0;
    715 }
     734    return internal_select_ex(s, writing, s->sock_timeout);
     735}
     736
     737/*
     738   Two macros for automatic retry of select() in case of false positives
     739   (for example, select() could indicate a socket is ready for reading
     740    but the data then discarded by the OS because of a wrong checksum).
     741   Here is an example of use:
     742
     743    BEGIN_SELECT_LOOP(s)
     744    Py_BEGIN_ALLOW_THREADS
     745    timeout = internal_select_ex(s, 0, interval);
     746    if (!timeout)
     747        outlen = recv(s->sock_fd, cbuf, len, flags);
     748    Py_END_ALLOW_THREADS
     749    if (timeout == 1) {
     750        PyErr_SetString(socket_timeout, "timed out");
     751        return -1;
     752    }
     753    END_SELECT_LOOP(s)
     754*/
     755#define BEGIN_SELECT_LOOP(s) \
     756    { \
     757        double deadline, interval = s->sock_timeout; \
     758        int has_timeout = s->sock_timeout > 0.0; \
     759        if (has_timeout) { \
     760            deadline = _PyTime_FloatTime() + s->sock_timeout; \
     761        } \
     762        while (1) { \
     763            errno = 0;
     764
     765#define END_SELECT_LOOP(s) \
     766            if (!has_timeout || \
     767                (!CHECK_ERRNO(EWOULDBLOCK) && !CHECK_ERRNO(EAGAIN))) \
     768                break; \
     769            interval = deadline - _PyTime_FloatTime(); \
     770        } \
     771    }
    716772
    717773/* Initialize a new socket object. */
     
    721777PyMODINIT_FUNC
    722778init_sockobject(PySocketSockObject *s,
    723                 SOCKET_T fd, int family, int type, int proto)
     779                SOCKET_T fd, int family, int type, int proto)
    724780{
    725781#ifdef RISCOS
    726         int block = 1;
    727 #endif
    728         s->sock_fd = fd;
    729         s->sock_family = family;
    730         s->sock_type = type;
    731         s->sock_proto = proto;
    732         s->sock_timeout = defaulttimeout;
    733 
    734         s->errorhandler = &set_error;
    735 
    736         if (defaulttimeout >= 0.0)
    737                 internal_setblocking(s, 0);
     782    int block = 1;
     783#endif
     784    s->sock_fd = fd;
     785    s->sock_family = family;
     786    s->sock_type = type;
     787    s->sock_proto = proto;
     788    s->sock_timeout = defaulttimeout;
     789
     790    s->errorhandler = &set_error;
     791
     792    if (defaulttimeout >= 0.0)
     793        internal_setblocking(s, 0);
    738794
    739795#ifdef RISCOS
    740         if (taskwindow)
    741                 socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
     796    if (taskwindow)
     797        socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
    742798#endif
    743799}
     
    752808new_sockobject(SOCKET_T fd, int family, int type, int proto)
    753809{
    754         PySocketSockObject *s;
    755         s = (PySocketSockObject *)
    756                 PyType_GenericNew(&sock_type, NULL, NULL);
    757         if (s != NULL)
    758                 init_sockobject(s, fd, family, type, proto);
    759         return s;
     810    PySocketSockObject *s;
     811    s = (PySocketSockObject *)
     812        PyType_GenericNew(&sock_type, NULL, NULL);
     813    if (s != NULL)
     814        init_sockobject(s, fd, family, type, proto);
     815    return s;
    760816}
    761817
     
    764820   thread to be in gethostbyname or getaddrinfo */
    765821#if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
    766 PyThread_type_lock netdb_lock;
     822static PyThread_type_lock netdb_lock;
    767823#endif
    768824
     
    777833setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
    778834{
    779         struct addrinfo hints, *res;
    780         int error;
    781         int d1, d2, d3, d4;
    782         char ch;
    783 
    784         memset((void *) addr_ret, '\0', sizeof(*addr_ret));
    785         if (name[0] == '\0') {
    786                 int siz;
    787                 memset(&hints, 0, sizeof(hints));
    788                 hints.ai_family = af;
    789                 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
    790                 hints.ai_flags = AI_PASSIVE;
    791                 Py_BEGIN_ALLOW_THREADS
    792                 ACQUIRE_GETADDRINFO_LOCK
    793                 error = getaddrinfo(NULL, "0", &hints, &res);
    794                 Py_END_ALLOW_THREADS
    795                 /* We assume that those thread-unsafe getaddrinfo() versions
    796                    *are* safe regarding their return value, ie. that a
    797                    subsequent call to getaddrinfo() does not destroy the
    798                    outcome of the first call. */
    799                 RELEASE_GETADDRINFO_LOCK
    800                 if (error) {
    801                         set_gaierror(error);
    802                         return -1;
    803                 }
    804                 switch (res->ai_family) {
    805                 case AF_INET:
    806                         siz = 4;
    807                         break;
     835    struct addrinfo hints, *res;
     836    int error;
     837    int d1, d2, d3, d4;
     838    char ch;
     839
     840    memset((void *) addr_ret, '\0', sizeof(*addr_ret));
     841    if (name[0] == '\0') {
     842        int siz;
     843        memset(&hints, 0, sizeof(hints));
     844        hints.ai_family = af;
     845        hints.ai_socktype = SOCK_DGRAM;         /*dummy*/
     846        hints.ai_flags = AI_PASSIVE;
     847        Py_BEGIN_ALLOW_THREADS
     848        ACQUIRE_GETADDRINFO_LOCK
     849        error = getaddrinfo(NULL, "0", &hints, &res);
     850        Py_END_ALLOW_THREADS
     851        /* We assume that those thread-unsafe getaddrinfo() versions
     852           *are* safe regarding their return value, ie. that a
     853           subsequent call to getaddrinfo() does not destroy the
     854           outcome of the first call. */
     855        RELEASE_GETADDRINFO_LOCK
     856        if (error) {
     857            set_gaierror(error);
     858            return -1;
     859        }
     860        switch (res->ai_family) {
     861        case AF_INET:
     862            siz = 4;
     863            break;
    808864#ifdef ENABLE_IPV6
    809                 case AF_INET6:
    810                         siz = 16;
    811                         break;
    812 #endif
    813                 default:
    814                         freeaddrinfo(res);
    815                         PyErr_SetString(socket_error,
    816                                 "unsupported address family");
    817                         return -1;
    818                 }
    819                 if (res->ai_next) {
    820                         freeaddrinfo(res);
    821                         PyErr_SetString(socket_error,
    822                                 "wildcard resolved to multiple address");
    823                         return -1;
    824                 }
    825                 if (res->ai_addrlen < addr_ret_size)
    826                         addr_ret_size = res->ai_addrlen;
    827                 memcpy(addr_ret, res->ai_addr, addr_ret_size);
    828                 freeaddrinfo(res);
    829                 return siz;
    830         }
    831         if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
    832                 struct sockaddr_in *sin;
    833                 if (af != AF_INET && af != AF_UNSPEC) {
    834                         PyErr_SetString(socket_error,
    835                                 "address family mismatched");
    836                         return -1;
    837                 }
    838                 sin = (struct sockaddr_in *)addr_ret;
    839                 memset((void *) sin, '\0', sizeof(*sin));
    840                 sin->sin_family = AF_INET;
     865        case AF_INET6:
     866            siz = 16;
     867            break;
     868#endif
     869        default:
     870            freeaddrinfo(res);
     871            PyErr_SetString(socket_error,
     872                "unsupported address family");
     873            return -1;
     874        }
     875        if (res->ai_next) {
     876            freeaddrinfo(res);
     877            PyErr_SetString(socket_error,
     878                "wildcard resolved to multiple address");
     879            return -1;
     880        }
     881        if (res->ai_addrlen < addr_ret_size)
     882            addr_ret_size = res->ai_addrlen;
     883        memcpy(addr_ret, res->ai_addr, addr_ret_size);
     884        freeaddrinfo(res);
     885        return siz;
     886    }
     887    if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
     888        struct sockaddr_in *sin;
     889        if (af != AF_INET && af != AF_UNSPEC) {
     890            PyErr_SetString(socket_error,
     891                "address family mismatched");
     892            return -1;
     893        }
     894        sin = (struct sockaddr_in *)addr_ret;
     895        memset((void *) sin, '\0', sizeof(*sin));
     896        sin->sin_family = AF_INET;
    841897#ifdef HAVE_SOCKADDR_SA_LEN
    842                 sin->sin_len = sizeof(*sin);
    843 #endif
    844                 sin->sin_addr.s_addr = INADDR_BROADCAST;
    845                 return sizeof(sin->sin_addr);
    846         }
    847         if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
    848             0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
    849             0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
    850                 struct sockaddr_in *sin;
    851                 sin = (struct sockaddr_in *)addr_ret;
    852                 sin->sin_addr.s_addr = htonl(
    853                         ((long) d1 << 24) | ((long) d2 << 16) |
    854                         ((long) d3 << 8) | ((long) d4 << 0));
    855                 sin->sin_family = AF_INET;
     898        sin->sin_len = sizeof(*sin);
     899#endif
     900        sin->sin_addr.s_addr = INADDR_BROADCAST;
     901        return sizeof(sin->sin_addr);
     902    }
     903    if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
     904        0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
     905        0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
     906        struct sockaddr_in *sin;
     907        sin = (struct sockaddr_in *)addr_ret;
     908        sin->sin_addr.s_addr = htonl(
     909            ((long) d1 << 24) | ((long) d2 << 16) |
     910            ((long) d3 << 8) | ((long) d4 << 0));
     911        sin->sin_family = AF_INET;
    856912#ifdef HAVE_SOCKADDR_SA_LEN
    857                 sin->sin_len = sizeof(*sin);
    858 #endif
    859                 return 4;
    860         }
    861         memset(&hints, 0, sizeof(hints));
    862         hints.ai_family = af;
    863         Py_BEGIN_ALLOW_THREADS
    864         ACQUIRE_GETADDRINFO_LOCK
    865         error = getaddrinfo(name, NULL, &hints, &res);
     913        sin->sin_len = sizeof(*sin);
     914#endif
     915        return 4;
     916    }
     917    memset(&hints, 0, sizeof(hints));
     918    hints.ai_family = af;
     919    Py_BEGIN_ALLOW_THREADS
     920    ACQUIRE_GETADDRINFO_LOCK
     921    error = getaddrinfo(name, NULL, &hints, &res);
    866922#if defined(__digital__) && defined(__unix__)
    867         if (error == EAI_NONAME && af == AF_UNSPEC) {
    868                 /* On Tru64 V5.1, numeric-to-addr conversion fails
    869                    if no address family is given. Assume IPv4 for now.*/
    870                 hints.ai_family = AF_INET;
    871                 error = getaddrinfo(name, NULL, &hints, &res);
    872         }
    873 #endif
    874         Py_END_ALLOW_THREADS
    875         RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
    876         if (error) {
    877                 set_gaierror(error);
    878                 return -1;
    879         }
    880         if (res->ai_addrlen < addr_ret_size)
    881                 addr_ret_size = res->ai_addrlen;
    882         memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
    883         freeaddrinfo(res);
    884         switch (addr_ret->sa_family) {
    885         case AF_INET:
    886                 return 4;
     923    if (error == EAI_NONAME && af == AF_UNSPEC) {
     924        /* On Tru64 V5.1, numeric-to-addr conversion fails
     925           if no address family is given. Assume IPv4 for now.*/
     926        hints.ai_family = AF_INET;
     927        error = getaddrinfo(name, NULL, &hints, &res);
     928    }
     929#endif
     930    Py_END_ALLOW_THREADS
     931    RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
     932    if (error) {
     933        set_gaierror(error);
     934        return -1;
     935    }
     936    if (res->ai_addrlen < addr_ret_size)
     937        addr_ret_size = res->ai_addrlen;
     938    memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
     939    freeaddrinfo(res);
     940    switch (addr_ret->sa_family) {
     941    case AF_INET:
     942        return 4;
    887943#ifdef ENABLE_IPV6
    888         case AF_INET6:
    889                 return 16;
    890 #endif
    891         default:
    892                 PyErr_SetString(socket_error, "unknown address family");
    893                 return -1;
    894         }
     944    case AF_INET6:
     945        return 16;
     946#endif
     947    default:
     948        PyErr_SetString(socket_error, "unknown address family");
     949        return -1;
     950    }
    895951}
    896952
     
    903959makeipaddr(struct sockaddr *addr, int addrlen)
    904960{
    905         char buf[NI_MAXHOST];
    906         int error;
    907 
    908         error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
    909                 NI_NUMERICHOST);
    910         if (error) {
    911                 set_gaierror(error);
    912                 return NULL;
    913         }
    914         return PyString_FromString(buf);
     961    char buf[NI_MAXHOST];
     962    int error;
     963
     964    error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
     965        NI_NUMERICHOST);
     966    if (error) {
     967        set_gaierror(error);
     968        return NULL;
     969    }
     970    return PyString_FromString(buf);
    915971}
    916972
     
    924980setbdaddr(char *name, bdaddr_t *bdaddr)
    925981{
    926         unsigned int b0, b1, b2, b3, b4, b5;
    927         char ch;
    928         int n;
    929 
    930         n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
    931                    &b5, &b4, &b3, &b2, &b1, &b0, &ch);
    932         if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
    933                 bdaddr->b[0] = b0;
    934                 bdaddr->b[1] = b1;
    935                 bdaddr->b[2] = b2;
    936                 bdaddr->b[3] = b3;
    937                 bdaddr->b[4] = b4;
    938                 bdaddr->b[5] = b5;
    939                 return 6;
    940         } else {
    941                 PyErr_SetString(socket_error, "bad bluetooth address");
    942                 return -1;
    943         }
     982    unsigned int b0, b1, b2, b3, b4, b5;
     983    char ch;
     984    int n;
     985
     986    n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
     987               &b5, &b4, &b3, &b2, &b1, &b0, &ch);
     988    if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
     989        bdaddr->b[0] = b0;
     990        bdaddr->b[1] = b1;
     991        bdaddr->b[2] = b2;
     992        bdaddr->b[3] = b3;
     993        bdaddr->b[4] = b4;
     994        bdaddr->b[5] = b5;
     995        return 6;
     996    } else {
     997        PyErr_SetString(socket_error, "bad bluetooth address");
     998        return -1;
     999    }
    9441000}
    9451001
     
    9511007makebdaddr(bdaddr_t *bdaddr)
    9521008{
    953         char buf[(6 * 2) + 5 + 1];
    954 
    955         sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
    956                 bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
    957                 bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
    958         return PyString_FromString(buf);
     1009    char buf[(6 * 2) + 5 + 1];
     1010
     1011    sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
     1012        bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
     1013        bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
     1014    return PyString_FromString(buf);
    9591015}
    9601016#endif
     
    9701026makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
    9711027{
    972         if (addrlen == 0) {
    973                 /* No address -- may be recvfrom() from known socket */
    974                 Py_INCREF(Py_None);
    975                 return Py_None;
    976         }
     1028    if (addrlen == 0) {
     1029        /* No address -- may be recvfrom() from known socket */
     1030        Py_INCREF(Py_None);
     1031        return Py_None;
     1032    }
    9771033
    9781034#ifdef __BEOS__
    979         /* XXX: BeOS version of accept() doesn't set family correctly */
    980         addr->sa_family = AF_INET;
    981 #endif
    982 
    983         switch (addr->sa_family) {
    984 
    985         case AF_INET:
    986         {
    987                 struct sockaddr_in *a;
    988                 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
    989                 PyObject *ret = NULL;
    990                 if (addrobj) {
    991                         a = (struct sockaddr_in *)addr;
    992                         ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
    993                         Py_DECREF(addrobj);
    994                 }
    995                 return ret;
    996         }
     1035    /* XXX: BeOS version of accept() doesn't set family correctly */
     1036    addr->sa_family = AF_INET;
     1037#endif
     1038
     1039    switch (addr->sa_family) {
     1040
     1041    case AF_INET:
     1042    {
     1043        struct sockaddr_in *a;
     1044        PyObject *addrobj = makeipaddr(addr, sizeof(*a));
     1045        PyObject *ret = NULL;
     1046        if (addrobj) {
     1047            a = (struct sockaddr_in *)addr;
     1048            ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
     1049            Py_DECREF(addrobj);
     1050        }
     1051        return ret;
     1052    }
    9971053
    9981054#if defined(AF_UNIX)
    999         case AF_UNIX:
    1000         {
    1001                 struct sockaddr_un *a = (struct sockaddr_un *) addr;
     1055    case AF_UNIX:
     1056    {
     1057        struct sockaddr_un *a = (struct sockaddr_un *) addr;
    10021058#ifdef linux
    1003                 if (a->sun_path[0] == 0) {  /* Linux abstract namespace */
    1004                         addrlen -= offsetof(struct sockaddr_un, sun_path);
    1005                         return PyString_FromStringAndSize(a->sun_path,
    1006                                                           addrlen);
    1007                 }
    1008                 else
     1059        if (a->sun_path[0] == 0) {  /* Linux abstract namespace */
     1060            addrlen -= offsetof(struct sockaddr_un, sun_path);
     1061            return PyString_FromStringAndSize(a->sun_path,
     1062                                              addrlen);
     1063        }
     1064        else
    10091065#endif /* linux */
    1010                 {
    1011                         /* regular NULL-terminated string */
    1012                         return PyString_FromString(a->sun_path);
    1013                 }
    1014         }
     1066        {
     1067            /* regular NULL-terminated string */
     1068            return PyString_FromString(a->sun_path);
     1069        }
     1070    }
    10151071#endif /* AF_UNIX */
    10161072
     
    10181074       case AF_NETLINK:
    10191075       {
    1020                struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
    1021                return Py_BuildValue("II", a->nl_pid, a->nl_groups);
     1076           struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
     1077           return Py_BuildValue("II", a->nl_pid, a->nl_groups);
    10221078       }
    10231079#endif /* AF_NETLINK */
    10241080
    10251081#ifdef ENABLE_IPV6
    1026         case AF_INET6:
    1027         {
    1028                 struct sockaddr_in6 *a;
    1029                 PyObject *addrobj = makeipaddr(addr, sizeof(*a));
    1030                 PyObject *ret = NULL;
    1031                 if (addrobj) {
    1032                         a = (struct sockaddr_in6 *)addr;
    1033                         ret = Py_BuildValue("Oiii",
    1034                                             addrobj,
    1035                                             ntohs(a->sin6_port),
    1036                                             a->sin6_flowinfo,
    1037                                             a->sin6_scope_id);
    1038                         Py_DECREF(addrobj);
    1039                 }
    1040                 return ret;
    1041         }
     1082    case AF_INET6:
     1083    {
     1084        struct sockaddr_in6 *a;
     1085        PyObject *addrobj = makeipaddr(addr, sizeof(*a));
     1086        PyObject *ret = NULL;
     1087        if (addrobj) {
     1088            a = (struct sockaddr_in6 *)addr;
     1089            ret = Py_BuildValue("OiII",
     1090                                addrobj,
     1091                                ntohs(a->sin6_port),
     1092                                ntohl(a->sin6_flowinfo),
     1093                                a->sin6_scope_id);
     1094            Py_DECREF(addrobj);
     1095        }
     1096        return ret;
     1097    }
    10421098#endif
    10431099
    10441100#ifdef USE_BLUETOOTH
    1045         case AF_BLUETOOTH:
    1046                 switch (proto) {
    1047 
    1048                 case BTPROTO_L2CAP:
    1049                 {
    1050                         struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
    1051                         PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
    1052                         PyObject *ret = NULL;
    1053                         if (addrobj) {
    1054                                 ret = Py_BuildValue("Oi",
    1055                                                     addrobj,
    1056                                                     _BT_L2_MEMB(a, psm));
    1057                                 Py_DECREF(addrobj);
    1058                         }
    1059                         return ret;
    1060                 }
    1061 
    1062                 case BTPROTO_RFCOMM:
    1063                 {
    1064                         struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
    1065                         PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
    1066                         PyObject *ret = NULL;
    1067                         if (addrobj) {
    1068                                 ret = Py_BuildValue("Oi",
    1069                                                     addrobj,
    1070                                                     _BT_RC_MEMB(a, channel));
    1071                                 Py_DECREF(addrobj);
    1072                         }
    1073                         return ret;
    1074                 }
    1075 
    1076                 case BTPROTO_HCI:
    1077                 {
    1078                         struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
    1079                         PyObject *ret = NULL;
    1080                         ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
    1081                         return ret;
    1082                 }
     1101    case AF_BLUETOOTH:
     1102        switch (proto) {
     1103
     1104        case BTPROTO_L2CAP:
     1105        {
     1106            struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
     1107            PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
     1108            PyObject *ret = NULL;
     1109            if (addrobj) {
     1110                ret = Py_BuildValue("Oi",
     1111                                    addrobj,
     1112                                    _BT_L2_MEMB(a, psm));
     1113                Py_DECREF(addrobj);
     1114            }
     1115            return ret;
     1116        }
     1117
     1118        case BTPROTO_RFCOMM:
     1119        {
     1120            struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
     1121            PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
     1122            PyObject *ret = NULL;
     1123            if (addrobj) {
     1124                ret = Py_BuildValue("Oi",
     1125                                    addrobj,
     1126                                    _BT_RC_MEMB(a, channel));
     1127                Py_DECREF(addrobj);
     1128            }
     1129            return ret;
     1130        }
     1131
     1132        case BTPROTO_HCI:
     1133        {
     1134            struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
     1135#if defined(__NetBSD__) || defined(__DragonFly__)
     1136            return makebdaddr(&_BT_HCI_MEMB(a, bdaddr));
     1137#else
     1138            PyObject *ret = NULL;
     1139            ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
     1140            return ret;
     1141#endif
     1142        }
    10831143
    10841144#if !defined(__FreeBSD__)
    1085                 case BTPROTO_SCO:
    1086                 {
    1087                         struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
    1088                         return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
    1089                 }
    1090 #endif
    1091 
    1092                 default:
    1093                         PyErr_SetString(PyExc_ValueError,
    1094                                         "Unknown Bluetooth protocol");
    1095                         return NULL;
    1096                 }
    1097 #endif
    1098 
    1099 #ifdef HAVE_NETPACKET_PACKET_H
    1100         case AF_PACKET:
    1101         {
    1102                 struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
    1103                 char *ifname = "";
    1104                 struct ifreq ifr;
    1105                 /* need to look up interface name give index */
    1106                 if (a->sll_ifindex) {
    1107                         ifr.ifr_ifindex = a->sll_ifindex;
    1108                         if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
    1109                                 ifname = ifr.ifr_name;
    1110                 }
    1111                 return Py_BuildValue("shbhs#",
    1112                                      ifname,
    1113                                      ntohs(a->sll_protocol),
    1114                                      a->sll_pkttype,
    1115                                      a->sll_hatype,
    1116                                      a->sll_addr,
    1117                                      a->sll_halen);
    1118         }
     1145        case BTPROTO_SCO:
     1146        {
     1147            struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
     1148            return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
     1149        }
     1150#endif
     1151
     1152        default:
     1153            PyErr_SetString(PyExc_ValueError,
     1154                            "Unknown Bluetooth protocol");
     1155            return NULL;
     1156        }
     1157#endif
     1158
     1159#if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFNAME)
     1160    case AF_PACKET:
     1161    {
     1162        struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
     1163        char *ifname = "";
     1164        struct ifreq ifr;
     1165        /* need to look up interface name give index */
     1166        if (a->sll_ifindex) {
     1167            ifr.ifr_ifindex = a->sll_ifindex;
     1168            if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
     1169                ifname = ifr.ifr_name;
     1170        }
     1171        return Py_BuildValue("shbhs#",
     1172                             ifname,
     1173                             ntohs(a->sll_protocol),
     1174                             a->sll_pkttype,
     1175                             a->sll_hatype,
     1176                             a->sll_addr,
     1177                             a->sll_halen);
     1178    }
    11191179#endif
    11201180
    11211181#ifdef HAVE_LINUX_TIPC_H
    1122         case AF_TIPC:
    1123         {
    1124                 struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
    1125                 if (a->addrtype == TIPC_ADDR_NAMESEQ) {
    1126                         return Py_BuildValue("IIIII",
    1127                                         a->addrtype,
    1128                                         a->addr.nameseq.type,
    1129                                         a->addr.nameseq.lower,
    1130                                         a->addr.nameseq.upper,
    1131                                         a->scope);
    1132                 } else if (a->addrtype == TIPC_ADDR_NAME) {
    1133                         return Py_BuildValue("IIIII",
    1134                                         a->addrtype,
    1135                                         a->addr.name.name.type,
    1136                                         a->addr.name.name.instance,
    1137                                         a->addr.name.name.instance,
    1138                                         a->scope);
    1139                 } else if (a->addrtype == TIPC_ADDR_ID) {
    1140                         return Py_BuildValue("IIIII",
    1141                                         a->addrtype,
    1142                                         a->addr.id.node,
    1143                                         a->addr.id.ref,
    1144                                         0,
    1145                                         a->scope);
    1146                 } else {
    1147                         PyErr_SetString(PyExc_ValueError,
    1148                                         "Invalid address type");
    1149                         return NULL;
    1150                 }
    1151         }
    1152 #endif
    1153 
    1154         /* More cases here... */
    1155 
    1156         default:
    1157                 /* If we don't know the address family, don't raise an
    1158                    exception -- return it as a tuple. */
    1159                 return Py_BuildValue("is#",
    1160                                      addr->sa_family,
    1161                                      addr->sa_data,
    1162                                      sizeof(addr->sa_data));
    1163 
    1164         }
     1182    case AF_TIPC:
     1183    {
     1184        struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
     1185        if (a->addrtype == TIPC_ADDR_NAMESEQ) {
     1186            return Py_BuildValue("IIIII",
     1187                            a->addrtype,
     1188                            a->addr.nameseq.type,
     1189                            a->addr.nameseq.lower,
     1190                            a->addr.nameseq.upper,
     1191                            a->scope);
     1192        } else if (a->addrtype == TIPC_ADDR_NAME) {
     1193            return Py_BuildValue("IIIII",
     1194                            a->addrtype,
     1195                            a->addr.name.name.type,
     1196                            a->addr.name.name.instance,
     1197                            a->addr.name.name.instance,
     1198                            a->scope);
     1199        } else if (a->addrtype == TIPC_ADDR_ID) {
     1200            return Py_BuildValue("IIIII",
     1201                            a->addrtype,
     1202                            a->addr.id.node,
     1203                            a->addr.id.ref,
     1204                            0,
     1205                            a->scope);
     1206        } else {
     1207            PyErr_SetString(PyExc_ValueError,
     1208                            "Invalid address type");
     1209            return NULL;
     1210        }
     1211    }
     1212#endif
     1213
     1214    /* More cases here... */
     1215
     1216    default:
     1217        /* If we don't know the address family, don't raise an
     1218           exception -- return it as a tuple. */
     1219        return Py_BuildValue("is#",
     1220                             addr->sa_family,
     1221                             addr->sa_data,
     1222                             sizeof(addr->sa_data));
     1223
     1224    }
    11651225}
    11661226
     
    11731233static int
    11741234getsockaddrarg(PySocketSockObject *s, PyObject *args,
    1175                struct sockaddr *addr_ret, int *len_ret)
    1176 {
    1177         switch (s->sock_family) {
     1235               struct sockaddr *addr_ret, int *len_ret)
     1236{
     1237    switch (s->sock_family) {
    11781238
    11791239#if defined(AF_UNIX)
    1180         case AF_UNIX:
    1181         {
    1182                 struct sockaddr_un* addr;
    1183                 char *path;
    1184                 int len;
    1185                 if (!PyArg_Parse(args, "t#", &path, &len))
    1186                         return 0;
    1187 
    1188                 addr = (struct sockaddr_un*)addr_ret;
     1240    case AF_UNIX:
     1241    {
     1242        struct sockaddr_un* addr;
     1243        char *path;
     1244        int len;
     1245        if (!PyArg_Parse(args, "t#", &path, &len))
     1246            return 0;
     1247
     1248        addr = (struct sockaddr_un*)addr_ret;
    11891249#ifdef linux
    1190                 if (len > 0 && path[0] == 0) {
    1191                         /* Linux abstract namespace extension */
    1192                         if (len > sizeof addr->sun_path) {
    1193                                 PyErr_SetString(socket_error,
    1194                                                 "AF_UNIX path too long");
    1195                                 return 0;
    1196                         }
    1197                 }
    1198                 else
     1250        if (len > 0 && path[0] == 0) {
     1251            /* Linux abstract namespace extension */
     1252            if (len > sizeof addr->sun_path) {
     1253                PyErr_SetString(socket_error,
     1254                                "AF_UNIX path too long");
     1255                return 0;
     1256            }
     1257        }
     1258        else
    11991259#endif /* linux */
    1200                 {
    1201                         /* regular NULL-terminated string */
    1202                         if (len >= sizeof addr->sun_path) {
    1203                                 PyErr_SetString(socket_error,
    1204                                                 "AF_UNIX path too long");
    1205                                 return 0;
    1206                         }
    1207                         addr->sun_path[len] = 0;
    1208                 }
    1209                 addr->sun_family = s->sock_family;
    1210                 memcpy(addr->sun_path, path, len);
     1260        {
     1261            /* regular NULL-terminated string */
     1262            if (len >= sizeof addr->sun_path) {
     1263                PyErr_SetString(socket_error,
     1264                                "AF_UNIX path too long");
     1265                return 0;
     1266            }
     1267            addr->sun_path[len] = 0;
     1268        }
     1269        addr->sun_family = s->sock_family;
     1270        memcpy(addr->sun_path, path, len);
    12111271#if defined(PYOS_OS2)
    1212                 *len_ret = sizeof(*addr);
    1213 #else
    1214                 *len_ret = len + offsetof(struct sockaddr_un, sun_path);
    1215 #endif
    1216                 return 1;
    1217         }
     1272        *len_ret = sizeof(*addr);
     1273#else
     1274        *len_ret = len + offsetof(struct sockaddr_un, sun_path);
     1275#endif
     1276        return 1;
     1277    }
    12181278#endif /* AF_UNIX */
    12191279
    12201280#if defined(AF_NETLINK)
    1221         case AF_NETLINK:
    1222         {
    1223                 struct sockaddr_nl* addr;
    1224                 int pid, groups;
    1225                 addr = (struct sockaddr_nl *)addr_ret;
    1226                 if (!PyTuple_Check(args)) {
    1227                         PyErr_Format(
    1228                                 PyExc_TypeError,
    1229                                 "getsockaddrarg: "
    1230                                 "AF_NETLINK address must be tuple, not %.500s",
    1231                                 Py_TYPE(args)->tp_name);
    1232                         return 0;
    1233                 }
    1234                 if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
    1235                         return 0;
    1236                 addr->nl_family = AF_NETLINK;
    1237                 addr->nl_pid = pid;
    1238                 addr->nl_groups = groups;
    1239                 *len_ret = sizeof(*addr);
    1240                 return 1;
    1241         }
    1242 #endif
    1243 
    1244         case AF_INET:
    1245         {
    1246                 struct sockaddr_in* addr;
    1247                 char *host;
    1248                 int port, result;
    1249                 if (!PyTuple_Check(args)) {
    1250                         PyErr_Format(
    1251                                 PyExc_TypeError,
    1252                                 "getsockaddrarg: "
    1253                                 "AF_INET address must be tuple, not %.500s",
    1254                                 Py_TYPE(args)->tp_name);
    1255                         return 0;
    1256                 }
    1257                 if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
    1258                                       "idna", &host, &port))
    1259                         return 0;
    1260                 addr=(struct sockaddr_in*)addr_ret;
    1261                 result = setipaddr(host, (struct sockaddr *)addr,
    1262                                    sizeof(*addr),  AF_INET);
    1263                 PyMem_Free(host);
    1264                 if (result < 0)
    1265                         return 0;
    1266                 addr->sin_family = AF_INET;
    1267                 addr->sin_port = htons((short)port);
    1268                 *len_ret = sizeof *addr;
    1269                 return 1;
    1270         }
     1281    case AF_NETLINK:
     1282    {
     1283        struct sockaddr_nl* addr;
     1284        int pid, groups;
     1285        addr = (struct sockaddr_nl *)addr_ret;
     1286        if (!PyTuple_Check(args)) {
     1287            PyErr_Format(
     1288                PyExc_TypeError,
     1289                "getsockaddrarg: "
     1290                "AF_NETLINK address must be tuple, not %.500s",
     1291                Py_TYPE(args)->tp_name);
     1292            return 0;
     1293        }
     1294        if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
     1295            return 0;
     1296        addr->nl_family = AF_NETLINK;
     1297        addr->nl_pid = pid;
     1298        addr->nl_groups = groups;
     1299        *len_ret = sizeof(*addr);
     1300        return 1;
     1301    }
     1302#endif
     1303
     1304    case AF_INET:
     1305    {
     1306        struct sockaddr_in* addr;
     1307        char *host;
     1308        int port, result;
     1309        if (!PyTuple_Check(args)) {
     1310            PyErr_Format(
     1311                PyExc_TypeError,
     1312                "getsockaddrarg: "
     1313                "AF_INET address must be tuple, not %.500s",
     1314                Py_TYPE(args)->tp_name);
     1315            return 0;
     1316        }
     1317        if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
     1318                              "idna", &host, &port))
     1319            return 0;
     1320        addr=(struct sockaddr_in*)addr_ret;
     1321        result = setipaddr(host, (struct sockaddr *)addr,
     1322                           sizeof(*addr),  AF_INET);
     1323        PyMem_Free(host);
     1324        if (result < 0)
     1325            return 0;
     1326        if (port < 0 || port > 0xffff) {
     1327            PyErr_SetString(
     1328                PyExc_OverflowError,
     1329                "getsockaddrarg: port must be 0-65535.");
     1330            return 0;
     1331        }
     1332        addr->sin_family = AF_INET;
     1333        addr->sin_port = htons((short)port);
     1334        *len_ret = sizeof *addr;
     1335        return 1;
     1336    }
    12711337
    12721338#ifdef ENABLE_IPV6
    1273         case AF_INET6:
    1274         {
    1275                 struct sockaddr_in6* addr;
    1276                 char *host;
    1277                 int port, flowinfo, scope_id, result;
    1278                 flowinfo = scope_id = 0;
    1279                 if (!PyTuple_Check(args)) {
    1280                         PyErr_Format(
    1281                                 PyExc_TypeError,
    1282                                 "getsockaddrarg: "
    1283                                 "AF_INET6 address must be tuple, not %.500s",
    1284                                 Py_TYPE(args)->tp_name);
    1285                         return 0;
    1286                 }
    1287                 if (!PyArg_ParseTuple(args, "eti|ii",
    1288                                       "idna", &host, &port, &flowinfo,
    1289                                       &scope_id)) {
    1290                         return 0;
    1291                 }
    1292                 addr = (struct sockaddr_in6*)addr_ret;
    1293                 result = setipaddr(host, (struct sockaddr *)addr,
    1294                                    sizeof(*addr), AF_INET6);
    1295                 PyMem_Free(host);
    1296                 if (result < 0)
    1297                         return 0;
    1298                 addr->sin6_family = s->sock_family;
    1299                 addr->sin6_port = htons((short)port);
    1300                 addr->sin6_flowinfo = flowinfo;
    1301                 addr->sin6_scope_id = scope_id;
    1302                 *len_ret = sizeof *addr;
    1303                 return 1;
    1304         }
     1339    case AF_INET6:
     1340    {
     1341        struct sockaddr_in6* addr;
     1342        char *host;
     1343        int port, result;
     1344        unsigned int flowinfo, scope_id;
     1345        flowinfo = scope_id = 0;
     1346        if (!PyTuple_Check(args)) {
     1347            PyErr_Format(
     1348                PyExc_TypeError,
     1349                "getsockaddrarg: "
     1350                "AF_INET6 address must be tuple, not %.500s",
     1351                Py_TYPE(args)->tp_name);
     1352            return 0;
     1353        }
     1354        if (!PyArg_ParseTuple(args, "eti|II",
     1355                              "idna", &host, &port, &flowinfo,
     1356                              &scope_id)) {
     1357            return 0;
     1358        }
     1359        addr = (struct sockaddr_in6*)addr_ret;
     1360        result = setipaddr(host, (struct sockaddr *)addr,
     1361                           sizeof(*addr), AF_INET6);
     1362        PyMem_Free(host);
     1363        if (result < 0)
     1364            return 0;
     1365        if (port < 0 || port > 0xffff) {
     1366            PyErr_SetString(
     1367                PyExc_OverflowError,
     1368                "getsockaddrarg: port must be 0-65535.");
     1369            return 0;
     1370        }
     1371        if (flowinfo > 0xfffff) {
     1372            PyErr_SetString(
     1373                PyExc_OverflowError,
     1374                "getsockaddrarg: flowinfo must be 0-1048575.");
     1375            return 0;
     1376        }
     1377        addr->sin6_family = s->sock_family;
     1378        addr->sin6_port = htons((short)port);
     1379        addr->sin6_flowinfo = htonl(flowinfo);
     1380        addr->sin6_scope_id = scope_id;
     1381        *len_ret = sizeof *addr;
     1382        return 1;
     1383    }
    13051384#endif
    13061385
    13071386#ifdef USE_BLUETOOTH
    1308         case AF_BLUETOOTH:
    1309         {
    1310                 switch (s->sock_proto) {
    1311                 case BTPROTO_L2CAP:
    1312                 {
    1313                         struct sockaddr_l2 *addr;
    1314                         char *straddr;
    1315 
    1316                         addr = (struct sockaddr_l2 *)addr_ret;
    1317                         _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
    1318                         if (!PyArg_ParseTuple(args, "si", &straddr,
    1319                                               &_BT_L2_MEMB(addr, psm))) {
    1320                                 PyErr_SetString(socket_error, "getsockaddrarg: "
    1321                                                 "wrong format");
    1322                                 return 0;
    1323                         }
    1324                         if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
    1325                                 return 0;
    1326 
    1327                         *len_ret = sizeof *addr;
    1328                         return 1;
    1329                 }
    1330                 case BTPROTO_RFCOMM:
    1331                 {
    1332                         struct sockaddr_rc *addr;
    1333                         char *straddr;
    1334 
    1335                         addr = (struct sockaddr_rc *)addr_ret;
    1336                         _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
    1337                         if (!PyArg_ParseTuple(args, "si", &straddr,
    1338                                               &_BT_RC_MEMB(addr, channel))) {
    1339                                 PyErr_SetString(socket_error, "getsockaddrarg: "
    1340                                                 "wrong format");
    1341                                 return 0;
    1342                         }
    1343                         if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
    1344                                 return 0;
    1345 
    1346                         *len_ret = sizeof *addr;
    1347                         return 1;
    1348                 }
    1349                 case BTPROTO_HCI:
    1350                 {
    1351                         struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
     1387    case AF_BLUETOOTH:
     1388    {
     1389        switch (s->sock_proto) {
     1390        case BTPROTO_L2CAP:
     1391        {
     1392            struct sockaddr_l2 *addr;
     1393            char *straddr;
     1394
     1395            addr = (struct sockaddr_l2 *)addr_ret;
     1396            memset(addr, 0, sizeof(struct sockaddr_l2));
     1397            _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
     1398            if (!PyArg_ParseTuple(args, "si", &straddr,
     1399                                  &_BT_L2_MEMB(addr, psm))) {
     1400                PyErr_SetString(socket_error, "getsockaddrarg: "
     1401                                "wrong format");
     1402                return 0;
     1403            }
     1404            if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
     1405                return 0;
     1406
     1407            *len_ret = sizeof *addr;
     1408            return 1;
     1409        }
     1410        case BTPROTO_RFCOMM:
     1411        {
     1412            struct sockaddr_rc *addr;
     1413            char *straddr;
     1414
     1415            addr = (struct sockaddr_rc *)addr_ret;
     1416            _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
     1417            if (!PyArg_ParseTuple(args, "si", &straddr,
     1418                                  &_BT_RC_MEMB(addr, channel))) {
     1419                PyErr_SetString(socket_error, "getsockaddrarg: "
     1420                                "wrong format");
     1421                return 0;
     1422            }
     1423            if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
     1424                return 0;
     1425
     1426            *len_ret = sizeof *addr;
     1427            return 1;
     1428        }
     1429        case BTPROTO_HCI:
     1430        {
     1431            struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
     1432#if defined(__NetBSD__) || defined(__DragonFly__)
     1433                        char *straddr = PyBytes_AS_STRING(args);
     1434
    13521435                        _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
    1353                         if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
    1354                                 PyErr_SetString(socket_error, "getsockaddrarg: "
    1355                                                 "wrong format");
    1356                                 return 0;
    1357                         }
    1358                         *len_ret = sizeof *addr;
    1359                         return 1;
    1360                 }
     1436            if (straddr == NULL) {
     1437                PyErr_SetString(socket_error, "getsockaddrarg: "
     1438                    "wrong format");
     1439                return 0;
     1440            }
     1441            if (setbdaddr(straddr, &_BT_HCI_MEMB(addr, bdaddr)) < 0)
     1442                return 0;
     1443#else
     1444            _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
     1445            if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
     1446                PyErr_SetString(socket_error, "getsockaddrarg: "
     1447                                "wrong format");
     1448                return 0;
     1449            }
     1450#endif
     1451            *len_ret = sizeof *addr;
     1452            return 1;
     1453        }
    13611454#if !defined(__FreeBSD__)
    1362                 case BTPROTO_SCO:
    1363                 {
    1364                         struct sockaddr_sco *addr;
    1365                         char *straddr;
    1366 
    1367                         addr = (struct sockaddr_sco *)addr_ret;
    1368                         _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
    1369                         straddr = PyString_AsString(args);
    1370                         if (straddr == NULL) {
    1371                                 PyErr_SetString(socket_error, "getsockaddrarg: "
    1372                                                 "wrong format");
    1373                                 return 0;
    1374                         }
    1375                         if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
    1376                                 return 0;
    1377 
    1378                         *len_ret = sizeof *addr;
    1379                         return 1;
    1380                 }
    1381 #endif
    1382                 default:
    1383                         PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
    1384                         return 0;
    1385                 }
    1386         }
    1387 #endif
    1388 
    1389 #ifdef HAVE_NETPACKET_PACKET_H
    1390         case AF_PACKET:
    1391         {
    1392                 struct sockaddr_ll* addr;
    1393                 struct ifreq ifr;
    1394                 char *interfaceName;
    1395                 int protoNumber;
    1396                 int hatype = 0;
    1397                 int pkttype = 0;
    1398                 char *haddr = NULL;
    1399                 unsigned int halen = 0;
    1400 
    1401                 if (!PyTuple_Check(args)) {
    1402                         PyErr_Format(
    1403                                 PyExc_TypeError,
    1404                                 "getsockaddrarg: "
    1405                                 "AF_PACKET address must be tuple, not %.500s",
    1406                                 Py_TYPE(args)->tp_name);
    1407                         return 0;
    1408                 }
    1409                 if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
    1410                                       &protoNumber, &pkttype, &hatype,
    1411                                       &haddr, &halen))
    1412                         return 0;
    1413                 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
    1414                 ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
    1415                 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
    1416                         s->errorhandler();
    1417                         return 0;
    1418                 }
    1419                 if (halen > 8) {
    1420                   PyErr_SetString(PyExc_ValueError,
    1421                                   "Hardware address must be 8 bytes or less");
    1422                   return 0;
    1423                 }
    1424                 addr = (struct sockaddr_ll*)addr_ret;
    1425                 addr->sll_family = AF_PACKET;
    1426                 addr->sll_protocol = htons((short)protoNumber);
    1427                 addr->sll_ifindex = ifr.ifr_ifindex;
    1428                 addr->sll_pkttype = pkttype;
    1429                 addr->sll_hatype = hatype;
    1430                 if (halen != 0) {
    1431                   memcpy(&addr->sll_addr, haddr, halen);
    1432                 }
    1433                 addr->sll_halen = halen;
    1434                 *len_ret = sizeof *addr;
    1435                 return 1;
    1436         }
     1455        case BTPROTO_SCO:
     1456        {
     1457            struct sockaddr_sco *addr;
     1458            char *straddr;
     1459
     1460            addr = (struct sockaddr_sco *)addr_ret;
     1461            _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
     1462            straddr = PyString_AsString(args);
     1463            if (straddr == NULL) {
     1464                PyErr_SetString(socket_error, "getsockaddrarg: "
     1465                                "wrong format");
     1466                return 0;
     1467            }
     1468            if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
     1469                return 0;
     1470
     1471            *len_ret = sizeof *addr;
     1472            return 1;
     1473        }
     1474#endif
     1475        default:
     1476            PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
     1477            return 0;
     1478        }
     1479    }
     1480#endif
     1481
     1482#if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFINDEX)
     1483    case AF_PACKET:
     1484    {
     1485        struct sockaddr_ll* addr;
     1486        struct ifreq ifr;
     1487        char *interfaceName;
     1488        int protoNumber;
     1489        int hatype = 0;
     1490        int pkttype = 0;
     1491        char *haddr = NULL;
     1492        unsigned int halen = 0;
     1493
     1494        if (!PyTuple_Check(args)) {
     1495            PyErr_Format(
     1496                PyExc_TypeError,
     1497                "getsockaddrarg: "
     1498                "AF_PACKET address must be tuple, not %.500s",
     1499                Py_TYPE(args)->tp_name);
     1500            return 0;
     1501        }
     1502        if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
     1503                              &protoNumber, &pkttype, &hatype,
     1504                              &haddr, &halen))
     1505            return 0;
     1506        strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
     1507        ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
     1508        if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
     1509            s->errorhandler();
     1510            return 0;
     1511        }
     1512        if (halen > 8) {
     1513          PyErr_SetString(PyExc_ValueError,
     1514                          "Hardware address must be 8 bytes or less");
     1515          return 0;
     1516        }
     1517        if (protoNumber < 0 || protoNumber > 0xffff) {
     1518            PyErr_SetString(
     1519                PyExc_OverflowError,
     1520                "getsockaddrarg: protoNumber must be 0-65535.");
     1521            return 0;
     1522        }
     1523        addr = (struct sockaddr_ll*)addr_ret;
     1524        addr->sll_family = AF_PACKET;
     1525        addr->sll_protocol = htons((short)protoNumber);
     1526        addr->sll_ifindex = ifr.ifr_ifindex;
     1527        addr->sll_pkttype = pkttype;
     1528        addr->sll_hatype = hatype;
     1529        if (halen != 0) {
     1530          memcpy(&addr->sll_addr, haddr, halen);
     1531        }
     1532        addr->sll_halen = halen;
     1533        *len_ret = sizeof *addr;
     1534        return 1;
     1535    }
    14371536#endif
    14381537
    14391538#ifdef HAVE_LINUX_TIPC_H
    1440         case AF_TIPC:
    1441         {
    1442                 unsigned int atype, v1, v2, v3;
    1443                 unsigned int scope = TIPC_CLUSTER_SCOPE;
    1444                 struct sockaddr_tipc *addr;
    1445 
    1446                 if (!PyTuple_Check(args)) {
    1447                         PyErr_Format(
    1448                                 PyExc_TypeError,
    1449                                 "getsockaddrarg: "
    1450                                 "AF_TIPC address must be tuple, not %.500s",
    1451                                 Py_TYPE(args)->tp_name);
    1452                         return 0;
    1453                 }
    1454 
    1455                 if (!PyArg_ParseTuple(args,
    1456                                         "IIII|I;Invalid TIPC address format",
    1457                                         &atype, &v1, &v2, &v3, &scope))
    1458                         return 0;
    1459 
    1460                 addr = (struct sockaddr_tipc *) addr_ret;
    1461                 memset(addr, 0, sizeof(struct sockaddr_tipc));
    1462 
    1463                 addr->family = AF_TIPC;
    1464                 addr->scope = scope;
    1465                 addr->addrtype = atype;
    1466 
    1467                 if (atype == TIPC_ADDR_NAMESEQ) {
    1468                         addr->addr.nameseq.type = v1;
    1469                         addr->addr.nameseq.lower = v2;
    1470                         addr->addr.nameseq.upper = v3;
    1471                 } else if (atype == TIPC_ADDR_NAME) {
    1472                         addr->addr.name.name.type = v1;
    1473                         addr->addr.name.name.instance = v2;
    1474                 } else if (atype == TIPC_ADDR_ID) {
    1475                         addr->addr.id.node = v1;
    1476                         addr->addr.id.ref = v2;
    1477                 } else {
    1478                         /* Shouldn't happen */
    1479                         PyErr_SetString(PyExc_TypeError, "Invalid address type");
    1480                         return 0;
    1481                 }
    1482 
    1483                 *len_ret = sizeof(*addr);
    1484 
    1485                 return 1;
    1486         }
    1487 #endif
    1488 
    1489         /* More cases here... */
    1490 
    1491         default:
    1492                 PyErr_SetString(socket_error, "getsockaddrarg: bad family");
    1493                 return 0;
    1494 
    1495         }
     1539    case AF_TIPC:
     1540    {
     1541        unsigned int atype, v1, v2, v3;
     1542        unsigned int scope = TIPC_CLUSTER_SCOPE;
     1543        struct sockaddr_tipc *addr;
     1544
     1545        if (!PyTuple_Check(args)) {
     1546            PyErr_Format(
     1547                PyExc_TypeError,
     1548                "getsockaddrarg: "
     1549                "AF_TIPC address must be tuple, not %.500s",
     1550                Py_TYPE(args)->tp_name);
     1551            return 0;
     1552        }
     1553
     1554        if (!PyArg_ParseTuple(args,
     1555                                "IIII|I;Invalid TIPC address format",
     1556                                &atype, &v1, &v2, &v3, &scope))
     1557            return 0;
     1558
     1559        addr = (struct sockaddr_tipc *) addr_ret;
     1560        memset(addr, 0, sizeof(struct sockaddr_tipc));
     1561
     1562        addr->family = AF_TIPC;
     1563        addr->scope = scope;
     1564        addr->addrtype = atype;
     1565
     1566        if (atype == TIPC_ADDR_NAMESEQ) {
     1567            addr->addr.nameseq.type = v1;
     1568            addr->addr.nameseq.lower = v2;
     1569            addr->addr.nameseq.upper = v3;
     1570        } else if (atype == TIPC_ADDR_NAME) {
     1571            addr->addr.name.name.type = v1;
     1572            addr->addr.name.name.instance = v2;
     1573        } else if (atype == TIPC_ADDR_ID) {
     1574            addr->addr.id.node = v1;
     1575            addr->addr.id.ref = v2;
     1576        } else {
     1577            /* Shouldn't happen */
     1578            PyErr_SetString(PyExc_TypeError, "Invalid address type");
     1579            return 0;
     1580        }
     1581
     1582        *len_ret = sizeof(*addr);
     1583
     1584        return 1;
     1585    }
     1586#endif
     1587
     1588    /* More cases here... */
     1589
     1590    default:
     1591        PyErr_SetString(socket_error, "getsockaddrarg: bad family");
     1592        return 0;
     1593
     1594    }
    14961595}
    14971596
     
    15041603getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
    15051604{
    1506         switch (s->sock_family) {
     1605    switch (s->sock_family) {
    15071606
    15081607#if defined(AF_UNIX)
    1509         case AF_UNIX:
    1510         {
    1511                 *len_ret = sizeof (struct sockaddr_un);
    1512                 return 1;
    1513         }
     1608    case AF_UNIX:
     1609    {
     1610        *len_ret = sizeof (struct sockaddr_un);
     1611        return 1;
     1612    }
    15141613#endif /* AF_UNIX */
    15151614#if defined(AF_NETLINK)
    15161615       case AF_NETLINK:
    15171616       {
    1518                *len_ret = sizeof (struct sockaddr_nl);
    1519                return 1;
     1617           *len_ret = sizeof (struct sockaddr_nl);
     1618           return 1;
    15201619       }
    15211620#endif
    15221621
    1523         case AF_INET:
    1524         {
    1525                 *len_ret = sizeof (struct sockaddr_in);
    1526                 return 1;
    1527         }
     1622    case AF_INET:
     1623    {
     1624        *len_ret = sizeof (struct sockaddr_in);
     1625        return 1;
     1626    }
    15281627
    15291628#ifdef ENABLE_IPV6
    1530         case AF_INET6:
    1531         {
    1532                 *len_ret = sizeof (struct sockaddr_in6);
    1533                 return 1;
    1534         }
     1629    case AF_INET6:
     1630    {
     1631        *len_ret = sizeof (struct sockaddr_in6);
     1632        return 1;
     1633    }
    15351634#endif
    15361635
    15371636#ifdef USE_BLUETOOTH
    1538         case AF_BLUETOOTH:
    1539         {
    1540                 switch(s->sock_proto)
    1541                 {
    1542 
    1543                 case BTPROTO_L2CAP:
    1544                         *len_ret = sizeof (struct sockaddr_l2);
    1545                         return 1;
    1546                 case BTPROTO_RFCOMM:
    1547                         *len_ret = sizeof (struct sockaddr_rc);
    1548                         return 1;
    1549                 case BTPROTO_HCI:
    1550                         *len_ret = sizeof (struct sockaddr_hci);
    1551                         return 1;
     1637    case AF_BLUETOOTH:
     1638    {
     1639        switch(s->sock_proto)
     1640        {
     1641
     1642        case BTPROTO_L2CAP:
     1643            *len_ret = sizeof (struct sockaddr_l2);
     1644            return 1;
     1645        case BTPROTO_RFCOMM:
     1646            *len_ret = sizeof (struct sockaddr_rc);
     1647            return 1;
     1648        case BTPROTO_HCI:
     1649            *len_ret = sizeof (struct sockaddr_hci);
     1650            return 1;
    15521651#if !defined(__FreeBSD__)
    1553                 case BTPROTO_SCO:
    1554                         *len_ret = sizeof (struct sockaddr_sco);
    1555                         return 1;
    1556 #endif
    1557                 default:
    1558                         PyErr_SetString(socket_error, "getsockaddrlen: "
    1559                                         "unknown BT protocol");
    1560                         return 0;
    1561 
    1562                 }
    1563         }
     1652        case BTPROTO_SCO:
     1653            *len_ret = sizeof (struct sockaddr_sco);
     1654            return 1;
     1655#endif
     1656        default:
     1657            PyErr_SetString(socket_error, "getsockaddrlen: "
     1658                            "unknown BT protocol");
     1659            return 0;
     1660
     1661        }
     1662    }
    15641663#endif
    15651664
    15661665#ifdef HAVE_NETPACKET_PACKET_H
    1567         case AF_PACKET:
    1568         {
    1569                 *len_ret = sizeof (struct sockaddr_ll);
    1570                 return 1;
    1571         }
     1666    case AF_PACKET:
     1667    {
     1668        *len_ret = sizeof (struct sockaddr_ll);
     1669        return 1;
     1670    }
    15721671#endif
    15731672
    15741673#ifdef HAVE_LINUX_TIPC_H
    1575         case AF_TIPC:
    1576         {
    1577                 *len_ret = sizeof (struct sockaddr_tipc);
    1578                 return 1;
    1579         }
    1580 #endif
    1581 
    1582         /* More cases here... */
    1583 
    1584         default:
    1585                 PyErr_SetString(socket_error, "getsockaddrlen: bad family");
    1586                 return 0;
    1587 
    1588         }
     1674    case AF_TIPC:
     1675    {
     1676        *len_ret = sizeof (struct sockaddr_tipc);
     1677        return 1;
     1678    }
     1679#endif
     1680
     1681    /* More cases here... */
     1682
     1683    default:
     1684        PyErr_SetString(socket_error, "getsockaddrlen: bad family");
     1685        return 0;
     1686
     1687    }
    15891688}
    15901689
     
    15951694sock_accept(PySocketSockObject *s)
    15961695{
    1597         sock_addr_t addrbuf;
    1598         SOCKET_T newfd;
    1599         socklen_t addrlen;
    1600         PyObject *sock = NULL;
    1601         PyObject *addr = NULL;
    1602         PyObject *res = NULL;
    1603         int timeout;
    1604 
    1605         if (!getsockaddrlen(s, &addrlen))
    1606                 return NULL;
    1607         memset(&addrbuf, 0, addrlen);
     1696    sock_addr_t addrbuf;
     1697    SOCKET_T newfd;
     1698    socklen_t addrlen;
     1699    PyObject *sock = NULL;
     1700    PyObject *addr = NULL;
     1701    PyObject *res = NULL;
     1702    int timeout;
     1703
     1704    if (!getsockaddrlen(s, &addrlen))
     1705        return NULL;
     1706    memset(&addrbuf, 0, addrlen);
    16081707
    16091708#ifdef MS_WINDOWS
    1610         newfd = INVALID_SOCKET;
    1611 #else
    1612         newfd = -1;
    1613 #endif
    1614 
    1615         if (!IS_SELECTABLE(s))
    1616                 return select_error();
    1617 
    1618         Py_BEGIN_ALLOW_THREADS
    1619         timeout = internal_select(s, 0);
    1620         if (!timeout)
    1621                 newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
    1622         Py_END_ALLOW_THREADS
    1623 
    1624         if (timeout == 1) {
    1625                 PyErr_SetString(socket_timeout, "timed out");
    1626                 return NULL;
    1627         }
     1709    newfd = INVALID_SOCKET;
     1710#else
     1711    newfd = -1;
     1712#endif
     1713
     1714    if (!IS_SELECTABLE(s))
     1715        return select_error();
     1716
     1717    BEGIN_SELECT_LOOP(s)
     1718    Py_BEGIN_ALLOW_THREADS
     1719    timeout = internal_select_ex(s, 0, interval);
     1720    if (!timeout)
     1721        newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
     1722    Py_END_ALLOW_THREADS
     1723
     1724    if (timeout == 1) {
     1725        PyErr_SetString(socket_timeout, "timed out");
     1726        return NULL;
     1727    }
     1728    END_SELECT_LOOP(s)
    16281729
    16291730#ifdef MS_WINDOWS
    1630         if (newfd == INVALID_SOCKET)
    1631 #else
    1632         if (newfd < 0)
    1633 #endif
    1634                 return s->errorhandler();
    1635 
    1636         /* Create the new object with unspecified family,
    1637            to avoid calls to bind() etc. on it. */
    1638         sock = (PyObject *) new_sockobject(newfd,
    1639                                            s->sock_family,
    1640                                            s->sock_type,
    1641                                            s->sock_proto);
    1642 
    1643         if (sock == NULL) {
    1644                 SOCKETCLOSE(newfd);
    1645                 goto finally;
    1646         }
    1647         addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
    1648                             addrlen, s->sock_proto);
    1649         if (addr == NULL)
    1650                 goto finally;
    1651 
    1652         res = PyTuple_Pack(2, sock, addr);
     1731    if (newfd == INVALID_SOCKET)
     1732#else
     1733    if (newfd < 0)
     1734#endif
     1735        return s->errorhandler();
     1736
     1737    /* Create the new object with unspecified family,
     1738       to avoid calls to bind() etc. on it. */
     1739    sock = (PyObject *) new_sockobject(newfd,
     1740                                       s->sock_family,
     1741                                       s->sock_type,
     1742                                       s->sock_proto);
     1743
     1744    if (sock == NULL) {
     1745        SOCKETCLOSE(newfd);
     1746        goto finally;
     1747    }
     1748    addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
     1749                        addrlen, s->sock_proto);
     1750    if (addr == NULL)
     1751        goto finally;
     1752
     1753    res = PyTuple_Pack(2, sock, addr);
    16531754
    16541755finally:
    1655         Py_XDECREF(sock);
    1656         Py_XDECREF(addr);
    1657         return res;
     1756    Py_XDECREF(sock);
     1757    Py_XDECREF(addr);
     1758    return res;
    16581759}
    16591760
     
    16731774sock_setblocking(PySocketSockObject *s, PyObject *arg)
    16741775{
    1675         int block;
    1676 
    1677         block = PyInt_AsLong(arg);
    1678         if (block == -1 && PyErr_Occurred())
    1679                 return NULL;
    1680 
    1681         s->sock_timeout = block ? -1.0 : 0.0;
    1682         internal_setblocking(s, block);
    1683 
    1684         Py_INCREF(Py_None);
    1685         return Py_None;
     1776    long block;
     1777
     1778    block = PyInt_AsLong(arg);
     1779    if (block == -1 && PyErr_Occurred())
     1780        return NULL;
     1781
     1782    s->sock_timeout = block ? -1.0 : 0.0;
     1783    internal_setblocking(s, block);
     1784
     1785    Py_INCREF(Py_None);
     1786    return Py_None;
    16861787}
    16871788
     
    17021803sock_settimeout(PySocketSockObject *s, PyObject *arg)
    17031804{
    1704         double timeout;
    1705 
    1706         if (arg == Py_None)
    1707                 timeout = -1.0;
    1708         else {
    1709                 timeout = PyFloat_AsDouble(arg);
    1710                 if (timeout < 0.0) {
    1711                         if (!PyErr_Occurred())
    1712                                 PyErr_SetString(PyExc_ValueError,
    1713                                                 "Timeout value out of range");
    1714                         return NULL;
    1715                 }
    1716         }
    1717 
    1718         s->sock_timeout = timeout;
    1719         internal_setblocking(s, timeout < 0.0);
    1720 
    1721         Py_INCREF(Py_None);
    1722         return Py_None;
     1805    double timeout;
     1806
     1807    if (arg == Py_None)
     1808        timeout = -1.0;
     1809    else {
     1810        timeout = PyFloat_AsDouble(arg);
     1811        if (timeout < 0.0) {
     1812            if (!PyErr_Occurred())
     1813                PyErr_SetString(PyExc_ValueError,
     1814                                "Timeout value out of range");
     1815            return NULL;
     1816        }
     1817    }
     1818
     1819    s->sock_timeout = timeout;
     1820    internal_setblocking(s, timeout < 0.0);
     1821
     1822    Py_INCREF(Py_None);
     1823    return Py_None;
    17231824}
    17241825
     
    17361837sock_gettimeout(PySocketSockObject *s)
    17371838{
    1738         if (s->sock_timeout < 0.0) {
    1739                 Py_INCREF(Py_None);
    1740                 return Py_None;
    1741         }
    1742         else
    1743                 return PyFloat_FromDouble(s->sock_timeout);
     1839    if (s->sock_timeout < 0.0) {
     1840        Py_INCREF(Py_None);
     1841        return Py_None;
     1842    }
     1843    else
     1844        return PyFloat_FromDouble(s->sock_timeout);
    17441845}
    17451846
     
    17471848"gettimeout() -> timeout\n\
    17481849\n\
    1749 Returns the timeout in floating seconds associated with socket \n\
     1850Returns the timeout in seconds (float) associated with socket \n\
    17501851operations. A timeout of None indicates that timeouts on socket \n\
    17511852operations are disabled.");
     
    17571858sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
    17581859{
    1759         int block;
    1760         block = PyInt_AsLong(arg);
    1761         if (block == -1 && PyErr_Occurred())
    1762                 return NULL;
    1763         Py_BEGIN_ALLOW_THREADS
    1764         socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
    1765         Py_END_ALLOW_THREADS
    1766 
    1767         Py_INCREF(Py_None);
    1768         return Py_None;
     1860    int block;
     1861    block = PyInt_AsLong(arg);
     1862    if (block == -1 && PyErr_Occurred())
     1863        return NULL;
     1864    Py_BEGIN_ALLOW_THREADS
     1865    socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
     1866    Py_END_ALLOW_THREADS
     1867
     1868    Py_INCREF(Py_None);
     1869    return Py_None;
    17691870}
    17701871PyDoc_STRVAR(sleeptaskw_doc,
     
    17831884sock_setsockopt(PySocketSockObject *s, PyObject *args)
    17841885{
    1785         int level;
    1786         int optname;
    1787         int res;
    1788         char *buf;
    1789         int buflen;
    1790         int flag;
    1791 
    1792         if (PyArg_ParseTuple(args, "iii:setsockopt",
    1793                              &level, &optname, &flag)) {
    1794                 buf = (char *) &flag;
    1795                 buflen = sizeof flag;
    1796         }
    1797         else {
    1798                 PyErr_Clear();
    1799                 if (!PyArg_ParseTuple(args, "iis#:setsockopt",
    1800                                       &level, &optname, &buf, &buflen))
    1801                         return NULL;
    1802         }
    1803         res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
    1804         if (res < 0)
    1805                 return s->errorhandler();
    1806         Py_INCREF(Py_None);
    1807         return Py_None;
     1886    int level;
     1887    int optname;
     1888    int res;
     1889    char *buf;
     1890    int buflen;
     1891    int flag;
     1892
     1893    if (PyArg_ParseTuple(args, "iii:setsockopt",
     1894                         &level, &optname, &flag)) {
     1895        buf = (char *) &flag;
     1896        buflen = sizeof flag;
     1897    }
     1898    else {
     1899        PyErr_Clear();
     1900        if (!PyArg_ParseTuple(args, "iis#:setsockopt",
     1901                              &level, &optname, &buf, &buflen))
     1902            return NULL;
     1903    }
     1904    res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
     1905    if (res < 0)
     1906        return s->errorhandler();
     1907    Py_INCREF(Py_None);
     1908    return Py_None;
    18081909}
    18091910
     
    18231924sock_getsockopt(PySocketSockObject *s, PyObject *args)
    18241925{
    1825         int level;
    1826         int optname;
    1827         int res;
    1828         PyObject *buf;
    1829         socklen_t buflen = 0;
     1926    int level;
     1927    int optname;
     1928    int res;
     1929    PyObject *buf;
     1930    socklen_t buflen = 0;
    18301931
    18311932#ifdef __BEOS__
    1832         /* We have incomplete socket support. */
    1833         PyErr_SetString(socket_error, "getsockopt not supported");
    1834         return NULL;
    1835 #else
    1836 
    1837         if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
    1838                               &level, &optname, &buflen))
    1839                 return NULL;
    1840 
    1841         if (buflen == 0) {
    1842                 int flag = 0;
    1843                 socklen_t flagsize = sizeof flag;
    1844                 res = getsockopt(s->sock_fd, level, optname,
    1845                                 (void *)&flag, &flagsize);
    1846                 if (res < 0)
    1847                         return s->errorhandler();
    1848                 return PyInt_FromLong(flag);
    1849         }
     1933    /* We have incomplete socket support. */
     1934    PyErr_SetString(socket_error, "getsockopt not supported");
     1935    return NULL;
     1936#else
     1937
     1938    if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
     1939                          &level, &optname, &buflen))
     1940        return NULL;
     1941
     1942    if (buflen == 0) {
     1943        int flag = 0;
     1944        socklen_t flagsize = sizeof flag;
     1945        res = getsockopt(s->sock_fd, level, optname,
     1946                        (void *)&flag, &flagsize);
     1947        if (res < 0)
     1948            return s->errorhandler();
     1949        return PyInt_FromLong(flag);
     1950    }
    18501951#ifdef __VMS
    1851         /* socklen_t is unsigned so no negative test is needed,
    1852            test buflen == 0 is previously done */
    1853         if (buflen > 1024) {
    1854 #else
    1855         if (buflen <= 0 || buflen > 1024) {
    1856 #endif
    1857                 PyErr_SetString(socket_error,
    1858                                 "getsockopt buflen out of range");
    1859                 return NULL;
    1860         }
    1861         buf = PyString_FromStringAndSize((char *)NULL, buflen);
    1862         if (buf == NULL)
    1863                 return NULL;
    1864         res = getsockopt(s->sock_fd, level, optname,
    1865                         (void *)PyString_AS_STRING(buf), &buflen);
    1866         if (res < 0) {
    1867                 Py_DECREF(buf);
    1868                 return s->errorhandler();
    1869         }
    1870         _PyString_Resize(&buf, buflen);
    1871         return buf;
     1952    /* socklen_t is unsigned so no negative test is needed,
     1953       test buflen == 0 is previously done */
     1954    if (buflen > 1024) {
     1955#else
     1956    if (buflen <= 0 || buflen > 1024) {
     1957#endif
     1958        PyErr_SetString(socket_error,
     1959                        "getsockopt buflen out of range");
     1960        return NULL;
     1961    }
     1962    buf = PyString_FromStringAndSize((char *)NULL, buflen);
     1963    if (buf == NULL)
     1964        return NULL;
     1965    res = getsockopt(s->sock_fd, level, optname,
     1966                    (void *)PyString_AS_STRING(buf), &buflen);
     1967    if (res < 0) {
     1968        Py_DECREF(buf);
     1969        return s->errorhandler();
     1970    }
     1971    _PyString_Resize(&buf, buflen);
     1972    return buf;
    18721973#endif /* __BEOS__ */
    18731974}
     
    18861987sock_bind(PySocketSockObject *s, PyObject *addro)
    18871988{
    1888         sock_addr_t addrbuf;
    1889         int addrlen;
    1890         int res;
    1891 
    1892         if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
    1893                 return NULL;
    1894         Py_BEGIN_ALLOW_THREADS
    1895         res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
    1896         Py_END_ALLOW_THREADS
    1897         if (res < 0)
    1898                 return s->errorhandler();
    1899         Py_INCREF(Py_None);
    1900         return Py_None;
     1989    sock_addr_t addrbuf;
     1990    int addrlen;
     1991    int res;
     1992
     1993    if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
     1994        return NULL;
     1995    Py_BEGIN_ALLOW_THREADS
     1996    res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
     1997    Py_END_ALLOW_THREADS
     1998    if (res < 0)
     1999        return s->errorhandler();
     2000    Py_INCREF(Py_None);
     2001    return Py_None;
    19012002}
    19022003
     
    19162017sock_close(PySocketSockObject *s)
    19172018{
    1918         SOCKET_T fd;
    1919 
    1920         if ((fd = s->sock_fd) != -1) {
    1921                 s->sock_fd = -1;
    1922                 Py_BEGIN_ALLOW_THREADS
    1923                 (void) SOCKETCLOSE(fd);
    1924                 Py_END_ALLOW_THREADS
    1925         }
    1926         Py_INCREF(Py_None);
    1927         return Py_None;
     2019    SOCKET_T fd;
     2020
     2021    if ((fd = s->sock_fd) != -1) {
     2022        s->sock_fd = -1;
     2023        Py_BEGIN_ALLOW_THREADS
     2024        (void) SOCKETCLOSE(fd);
     2025        Py_END_ALLOW_THREADS
     2026    }
     2027    Py_INCREF(Py_None);
     2028    return Py_None;
    19282029}
    19292030
     
    19352036static int
    19362037internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
    1937                 int *timeoutp)
    1938 {
    1939         int res, timeout;
    1940 
    1941         timeout = 0;
    1942         res = connect(s->sock_fd, addr, addrlen);
     2038                int *timeoutp)
     2039{
     2040    int res, timeout;
     2041
     2042    timeout = 0;
     2043    res = connect(s->sock_fd, addr, addrlen);
    19432044
    19442045#ifdef MS_WINDOWS
    19452046
    1946         if (s->sock_timeout > 0.0) {
    1947                 if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
    1948                     IS_SELECTABLE(s)) {
    1949                         /* This is a mess.  Best solution: trust select */
    1950                         fd_set fds;
    1951                         fd_set fds_exc;
    1952                         struct timeval tv;
    1953                         tv.tv_sec = (int)s->sock_timeout;
    1954                         tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
    1955                         FD_ZERO(&fds);
    1956                         FD_SET(s->sock_fd, &fds);
    1957                         FD_ZERO(&fds_exc);
    1958                         FD_SET(s->sock_fd, &fds_exc);
    1959                         res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
    1960                         if (res == 0) {
    1961                                 res = WSAEWOULDBLOCK;
    1962                                 timeout = 1;
    1963                         } else if (res > 0) {
    1964                                 if (FD_ISSET(s->sock_fd, &fds))
    1965                                         /* The socket is in the writeable set - this
    1966                                            means connected */
    1967                                         res = 0;
    1968                                 else {
    1969                                         /* As per MS docs, we need to call getsockopt()
    1970                                            to get the underlying error */
    1971                                         int res_size = sizeof res;
    1972                                         /* It must be in the exception set */
    1973                                         assert(FD_ISSET(s->sock_fd, &fds_exc));
    1974                                         if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
    1975                                                             (char *)&res, &res_size))
    1976                                                 /* getsockopt also clears WSAGetLastError,
    1977                                                    so reset it back. */
    1978                                                 WSASetLastError(res);
    1979                                         else
    1980                                                 res = WSAGetLastError();
    1981                                 }
    1982                         }
    1983                         /* else if (res < 0) an error occurred */
    1984                 }
    1985         }
    1986 
    1987         if (res < 0)
    1988                 res = WSAGetLastError();
    1989 
    1990 #else
    1991 
    1992         if (s->sock_timeout > 0.0) {
    1993                 if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
    1994                         timeout = internal_select(s, 1);
    1995                         if (timeout == 0) {
    1996                                 /* Bug #1019808: in case of an EINPROGRESS,
    1997                                    use getsockopt(SO_ERROR) to get the real
    1998                                    error. */
    1999                                 socklen_t res_size = sizeof res;
    2000                                 (void)getsockopt(s->sock_fd, SOL_SOCKET,
    2001                                                  SO_ERROR, &res, &res_size);
    2002                                 if (res == EISCONN)
    2003                                         res = 0;
    2004                                 errno = res;
    2005                         }
    2006                         else if (timeout == -1) {
    2007                                 res = errno;            /* had error */
    2008                         }
    2009                         else
    2010                                 res = EWOULDBLOCK;      /* timed out */
    2011                 }
    2012         }
    2013 
    2014         if (res < 0)
    2015                 res = errno;
    2016 
    2017 #endif
    2018         *timeoutp = timeout;
    2019 
    2020         return res;
     2047    if (s->sock_timeout > 0.0) {
     2048        if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
     2049            IS_SELECTABLE(s)) {
     2050            /* This is a mess.  Best solution: trust select */
     2051            fd_set fds;
     2052            fd_set fds_exc;
     2053            struct timeval tv;
     2054            tv.tv_sec = (int)s->sock_timeout;
     2055            tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
     2056            FD_ZERO(&fds);
     2057            FD_SET(s->sock_fd, &fds);
     2058            FD_ZERO(&fds_exc);
     2059            FD_SET(s->sock_fd, &fds_exc);
     2060            res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
     2061            if (res == 0) {
     2062                res = WSAEWOULDBLOCK;
     2063                timeout = 1;
     2064            } else if (res > 0) {
     2065                if (FD_ISSET(s->sock_fd, &fds))
     2066                    /* The socket is in the writeable set - this
     2067                       means connected */
     2068                    res = 0;
     2069                else {
     2070                    /* As per MS docs, we need to call getsockopt()
     2071                       to get the underlying error */
     2072                    int res_size = sizeof res;
     2073                    /* It must be in the exception set */
     2074                    assert(FD_ISSET(s->sock_fd, &fds_exc));
     2075                    if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
     2076                                        (char *)&res, &res_size))
     2077                        /* getsockopt also clears WSAGetLastError,
     2078                           so reset it back. */
     2079                        WSASetLastError(res);
     2080                    else
     2081                        res = WSAGetLastError();
     2082                }
     2083            }
     2084            /* else if (res < 0) an error occurred */
     2085        }
     2086    }
     2087
     2088    if (res < 0)
     2089        res = WSAGetLastError();
     2090
     2091#else
     2092
     2093    if (s->sock_timeout > 0.0) {
     2094        if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
     2095            timeout = internal_select(s, 1);
     2096            if (timeout == 0) {
     2097                /* Bug #1019808: in case of an EINPROGRESS,
     2098                   use getsockopt(SO_ERROR) to get the real
     2099                   error. */
     2100                socklen_t res_size = sizeof res;
     2101                (void)getsockopt(s->sock_fd, SOL_SOCKET,
     2102                                 SO_ERROR, &res, &res_size);
     2103                if (res == EISCONN)
     2104                    res = 0;
     2105                errno = res;
     2106            }
     2107            else if (timeout == -1) {
     2108                res = errno;            /* had error */
     2109            }
     2110            else
     2111                res = EWOULDBLOCK;                      /* timed out */
     2112        }
     2113    }
     2114
     2115    if (res < 0)
     2116        res = errno;
     2117
     2118#endif
     2119    *timeoutp = timeout;
     2120
     2121    return res;
    20212122}
    20222123
     
    20262127sock_connect(PySocketSockObject *s, PyObject *addro)
    20272128{
    2028         sock_addr_t addrbuf;
    2029         int addrlen;
    2030         int res;
    2031         int timeout;
    2032 
    2033         if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
    2034                 return NULL;
    2035 
    2036         Py_BEGIN_ALLOW_THREADS
    2037         res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
    2038         Py_END_ALLOW_THREADS
    2039 
    2040         if (timeout == 1) {
    2041                 PyErr_SetString(socket_timeout, "timed out");
    2042                 return NULL;
    2043         }
    2044         if (res != 0)
    2045                 return s->errorhandler();
    2046         Py_INCREF(Py_None);
    2047         return Py_None;
     2129    sock_addr_t addrbuf;
     2130    int addrlen;
     2131    int res;
     2132    int timeout;
     2133
     2134    if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
     2135        return NULL;
     2136
     2137    Py_BEGIN_ALLOW_THREADS
     2138    res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
     2139    Py_END_ALLOW_THREADS
     2140
     2141    if (timeout == 1) {
     2142        PyErr_SetString(socket_timeout, "timed out");
     2143        return NULL;
     2144    }
     2145    if (res != 0)
     2146        return s->errorhandler();
     2147    Py_INCREF(Py_None);
     2148    return Py_None;
    20482149}
    20492150
     
    20602161sock_connect_ex(PySocketSockObject *s, PyObject *addro)
    20612162{
    2062         sock_addr_t addrbuf;
    2063         int addrlen;
    2064         int res;
    2065         int timeout;
    2066 
    2067         if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
    2068                 return NULL;
    2069 
    2070         Py_BEGIN_ALLOW_THREADS
    2071         res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
    2072         Py_END_ALLOW_THREADS
    2073 
    2074         /* Signals are not errors (though they may raise exceptions).  Adapted
    2075            from PyErr_SetFromErrnoWithFilenameObject(). */
     2163    sock_addr_t addrbuf;
     2164    int addrlen;
     2165    int res;
     2166    int timeout;
     2167
     2168    if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
     2169        return NULL;
     2170
     2171    Py_BEGIN_ALLOW_THREADS
     2172    res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
     2173    Py_END_ALLOW_THREADS
     2174
     2175    /* Signals are not errors (though they may raise exceptions).  Adapted
     2176       from PyErr_SetFromErrnoWithFilenameObject(). */
    20762177#ifdef EINTR
    2077         if (res == EINTR && PyErr_CheckSignals())
    2078                 return NULL;
    2079 #endif
    2080 
    2081         return PyInt_FromLong((long) res);
     2178    if (res == EINTR && PyErr_CheckSignals())
     2179        return NULL;
     2180#endif
     2181
     2182    return PyInt_FromLong((long) res);
    20822183}
    20832184
     
    20952196{
    20962197#if SIZEOF_SOCKET_T <= SIZEOF_LONG
    2097         return PyInt_FromLong((long) s->sock_fd);
    2098 #else
    2099         return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
     2198    return PyInt_FromLong((long) s->sock_fd);
     2199#else
     2200    return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
    21002201#endif
    21012202}
     
    21132214sock_dup(PySocketSockObject *s)
    21142215{
    2115         SOCKET_T newfd;
    2116         PyObject *sock;
    2117 
    2118         newfd = dup(s->sock_fd);
    2119         if (newfd < 0)
    2120                 return s->errorhandler();
    2121         sock = (PyObject *) new_sockobject(newfd,
    2122                                            s->sock_family,
    2123                                            s->sock_type,
    2124                                            s->sock_proto);
    2125         if (sock == NULL)
    2126                 SOCKETCLOSE(newfd);
    2127         return sock;
     2216    SOCKET_T newfd;
     2217    PyObject *sock;
     2218
     2219    newfd = dup(s->sock_fd);
     2220    if (newfd < 0)
     2221        return s->errorhandler();
     2222    sock = (PyObject *) new_sockobject(newfd,
     2223                                       s->sock_family,
     2224                                       s->sock_type,
     2225                                       s->sock_proto);
     2226    if (sock == NULL)
     2227        SOCKETCLOSE(newfd);
     2228    return sock;
    21282229}
    21292230
     
    21412242sock_getsockname(PySocketSockObject *s)
    21422243{
    2143         sock_addr_t addrbuf;
    2144         int res;
    2145         socklen_t addrlen;
    2146 
    2147         if (!getsockaddrlen(s, &addrlen))
    2148                 return NULL;
    2149         memset(&addrbuf, 0, addrlen);
    2150         Py_BEGIN_ALLOW_THREADS
    2151         res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
    2152         Py_END_ALLOW_THREADS
    2153         if (res < 0)
    2154                 return s->errorhandler();
    2155         return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
    2156                             s->sock_proto);
     2244    sock_addr_t addrbuf;
     2245    int res;
     2246    socklen_t addrlen;
     2247
     2248    if (!getsockaddrlen(s, &addrlen))
     2249        return NULL;
     2250    memset(&addrbuf, 0, addrlen);
     2251    Py_BEGIN_ALLOW_THREADS
     2252    res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
     2253    Py_END_ALLOW_THREADS
     2254    if (res < 0)
     2255        return s->errorhandler();
     2256    return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
     2257                        s->sock_proto);
    21572258}
    21582259
     
    21642265
    21652266
    2166 #ifdef HAVE_GETPEERNAME         /* Cray APP doesn't have this :-( */
     2267#ifdef HAVE_GETPEERNAME         /* Cray APP doesn't have this :-( */
    21672268/* s.getpeername() method */
    21682269
     
    21702271sock_getpeername(PySocketSockObject *s)
    21712272{
    2172         sock_addr_t addrbuf;
    2173         int res;
    2174         socklen_t addrlen;
    2175 
    2176         if (!getsockaddrlen(s, &addrlen))
    2177                 return NULL;
    2178         memset(&addrbuf, 0, addrlen);
    2179         Py_BEGIN_ALLOW_THREADS
    2180         res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
    2181         Py_END_ALLOW_THREADS
    2182         if (res < 0)
    2183                 return s->errorhandler();
    2184         return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
    2185                             s->sock_proto);
     2273    sock_addr_t addrbuf;
     2274    int res;
     2275    socklen_t addrlen;
     2276
     2277    if (!getsockaddrlen(s, &addrlen))
     2278        return NULL;
     2279    memset(&addrbuf, 0, addrlen);
     2280    Py_BEGIN_ALLOW_THREADS
     2281    res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
     2282    Py_END_ALLOW_THREADS
     2283    if (res < 0)
     2284        return s->errorhandler();
     2285    return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
     2286                        s->sock_proto);
    21862287}
    21872288
     
    22002301sock_listen(PySocketSockObject *s, PyObject *arg)
    22012302{
    2202         int backlog;
    2203         int res;
    2204 
    2205         backlog = PyInt_AsLong(arg);
    2206         if (backlog == -1 && PyErr_Occurred())
    2207                 return NULL;
    2208         Py_BEGIN_ALLOW_THREADS
    2209         if (backlog < 1)
    2210                 backlog = 1;
    2211         res = listen(s->sock_fd, backlog);
    2212         Py_END_ALLOW_THREADS
    2213         if (res < 0)
    2214                 return s->errorhandler();
    2215         Py_INCREF(Py_None);
    2216         return Py_None;
     2303    int backlog;
     2304    int res;
     2305
     2306    backlog = _PyInt_AsInt(arg);
     2307    if (backlog == -1 && PyErr_Occurred())
     2308        return NULL;
     2309    Py_BEGIN_ALLOW_THREADS
     2310    /* To avoid problems on systems that don't allow a negative backlog
     2311     * (which doesn't make sense anyway) we force a minimum value of 0. */
     2312    if (backlog < 0)
     2313        backlog = 0;
     2314    res = listen(s->sock_fd, backlog);
     2315    Py_END_ALLOW_THREADS
     2316    if (res < 0)
     2317        return s->errorhandler();
     2318    Py_INCREF(Py_None);
     2319    return Py_None;
    22172320}
    22182321
     
    22212324\n\
    22222325Enable a server to accept connections.  The backlog argument must be at\n\
    2223 least 1; it specifies the number of unaccepted connection that the system\n\
    2224 will allow before refusing new connections.");
     2326least 0 (if it is lower, it is set to 0); it specifies the number of\n\
     2327unaccepted connections that the system will allow before refusing new\n\
     2328connections.");
    22252329
    22262330
     
    22362340sock_makefile(PySocketSockObject *s, PyObject *args)
    22372341{
    2238         extern int fclose(FILE *);
    2239         char *mode = "r";
    2240         int bufsize = -1;
     2342    extern int fclose(FILE *);
     2343    char *mode = "r";
     2344    int bufsize = -1;
    22412345#ifdef MS_WIN32
    2242         Py_intptr_t fd;
    2243 #else
    2244         int fd;
    2245 #endif
    2246         FILE *fp;
    2247         PyObject *f;
     2346    Py_intptr_t fd;
     2347#else
     2348    int fd;
     2349#endif
     2350    FILE *fp;
     2351    PyObject *f;
    22482352#ifdef __VMS
    2249         char *mode_r = "r";
    2250         char *mode_w = "w";
    2251 #endif
    2252 
    2253         if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
    2254                 return NULL;
     2353    char *mode_r = "r";
     2354    char *mode_w = "w";
     2355#endif
     2356
     2357    if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
     2358        return NULL;
    22552359#ifdef __VMS
    2256         if (strcmp(mode,"rb") == 0) {
    2257             mode = mode_r;
    2258         }
    2259         else {
    2260                 if (strcmp(mode,"wb") == 0) {
    2261                         mode = mode_w;
    2262                 }
    2263         }
     2360    if (strcmp(mode,"rb") == 0) {
     2361        mode = mode_r;
     2362    }
     2363    else {
     2364        if (strcmp(mode,"wb") == 0) {
     2365            mode = mode_w;
     2366        }
     2367    }
    22642368#endif
    22652369#ifdef MS_WIN32
    2266         if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
    2267             ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
    2268 #else
    2269         if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
    2270 #endif
    2271         {
    2272                 if (fd >= 0)
    2273                         SOCKETCLOSE(fd);
    2274                 return s->errorhandler();
    2275         }
    2276         f = PyFile_FromFile(fp, "<socket>", mode, fclose);
    2277         if (f != NULL)
    2278                 PyFile_SetBufSize(f, bufsize);
    2279         return f;
     2370    if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
     2371        ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
     2372#else
     2373    if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
     2374#endif
     2375    {
     2376        if (fd >= 0)
     2377            SOCKETCLOSE(fd);
     2378        return s->errorhandler();
     2379    }
     2380    f = PyFile_FromFile(fp, "<socket>", mode, fclose);
     2381    if (f != NULL)
     2382        PyFile_SetBufSize(f, bufsize);
     2383    return f;
    22802384}
    22812385
     
    22922396 * char buffer.  If you have any inc/dec ref to do to the objects that contain
    22932397 * the buffer, do it in the caller.  This function returns the number of bytes
    2294  * succesfully read.  If there was an error, it returns -1.  Note that it is
     2398 * successfully read.  If there was an error, it returns -1.  Note that it is
    22952399 * also possible that we return a number of bytes smaller than the request
    22962400 * bytes.
     
    22992403sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
    23002404{
    2301         ssize_t outlen = -1;
    2302         int timeout;
     2405    ssize_t outlen = -1;
     2406    int timeout;
    23032407#ifdef __VMS
    2304         int remaining;
    2305         char *read_buf;
    2306 #endif
    2307 
    2308         if (!IS_SELECTABLE(s)) {
    2309                 select_error();
    2310                 return -1;
    2311         }
     2408    int remaining;
     2409    char *read_buf;
     2410#endif
     2411
     2412    if (!IS_SELECTABLE(s)) {
     2413        select_error();
     2414        return -1;
     2415    }
    23122416
    23132417#ifndef __VMS
    2314         Py_BEGIN_ALLOW_THREADS
    2315         timeout = internal_select(s, 0);
    2316         if (!timeout)
    2317                 outlen = recv(s->sock_fd, cbuf, len, flags);
    2318         Py_END_ALLOW_THREADS
    2319 
    2320         if (timeout == 1) {
    2321                 PyErr_SetString(socket_timeout, "timed out");
    2322                 return -1;
    2323         }
    2324         if (outlen < 0) {
    2325                 /* Note: the call to errorhandler() ALWAYS indirectly returned
    2326                    NULL, so ignore its return value */
    2327                 s->errorhandler();
    2328                 return -1;
    2329         }
    2330 #else
    2331         read_buf = cbuf;
    2332         remaining = len;
    2333         while (remaining != 0) {
    2334                 unsigned int segment;
    2335                 int nread = -1;
    2336 
    2337                 segment = remaining /SEGMENT_SIZE;
    2338                 if (segment != 0) {
    2339                         segment = SEGMENT_SIZE;
    2340                 }
    2341                 else {
    2342                         segment = remaining;
    2343                 }
    2344 
    2345                 Py_BEGIN_ALLOW_THREADS
    2346                 timeout = internal_select(s, 0);
    2347                 if (!timeout)
    2348                         nread = recv(s->sock_fd, read_buf, segment, flags);
    2349                 Py_END_ALLOW_THREADS
    2350 
    2351                 if (timeout == 1) {
    2352                         PyErr_SetString(socket_timeout, "timed out");
    2353                         return -1;
    2354                 }
    2355                 if (nread < 0) {
    2356                         s->errorhandler();
    2357                         return -1;
    2358                 }
    2359                 if (nread != remaining) {
    2360                         read_buf += nread;
    2361                         break;
    2362                 }
    2363 
    2364                 remaining -= segment;
    2365                 read_buf += segment;
    2366         }
    2367         outlen = read_buf - cbuf;
     2418    BEGIN_SELECT_LOOP(s)
     2419    Py_BEGIN_ALLOW_THREADS
     2420    timeout = internal_select_ex(s, 0, interval);
     2421    if (!timeout)
     2422        outlen = recv(s->sock_fd, cbuf, len, flags);
     2423    Py_END_ALLOW_THREADS
     2424
     2425    if (timeout == 1) {
     2426        PyErr_SetString(socket_timeout, "timed out");
     2427        return -1;
     2428    }
     2429    END_SELECT_LOOP(s)
     2430    if (outlen < 0) {
     2431        /* Note: the call to errorhandler() ALWAYS indirectly returned
     2432           NULL, so ignore its return value */
     2433        s->errorhandler();
     2434        return -1;
     2435    }
     2436#else
     2437    read_buf = cbuf;
     2438    remaining = len;
     2439    while (remaining != 0) {
     2440        unsigned int segment;
     2441        int nread = -1;
     2442
     2443        segment = remaining /SEGMENT_SIZE;
     2444        if (segment != 0) {
     2445            segment = SEGMENT_SIZE;
     2446        }
     2447        else {
     2448            segment = remaining;
     2449        }
     2450
     2451        BEGIN_SELECT_LOOP(s)
     2452        Py_BEGIN_ALLOW_THREADS
     2453        timeout = internal_select_ex(s, 0, interval);
     2454        if (!timeout)
     2455            nread = recv(s->sock_fd, read_buf, segment, flags);
     2456        Py_END_ALLOW_THREADS
     2457
     2458        if (timeout == 1) {
     2459            PyErr_SetString(socket_timeout, "timed out");
     2460            return -1;
     2461        }
     2462        END_SELECT_LOOP(s)
     2463
     2464        if (nread < 0) {
     2465            s->errorhandler();
     2466            return -1;
     2467        }
     2468        if (nread != remaining) {
     2469            read_buf += nread;
     2470            break;
     2471        }
     2472
     2473        remaining -= segment;
     2474        read_buf += segment;
     2475    }
     2476    outlen = read_buf - cbuf;
    23682477#endif /* !__VMS */
    23692478
    2370         return outlen;
     2479    return outlen;
    23712480}
    23722481
     
    23772486sock_recv(PySocketSockObject *s, PyObject *args)
    23782487{
    2379         int recvlen, flags = 0;
    2380         ssize_t outlen;
    2381         PyObject *buf;
    2382 
    2383         if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
    2384                 return NULL;
    2385 
    2386         if (recvlen < 0) {
    2387                 PyErr_SetString(PyExc_ValueError,
    2388                                 "negative buffersize in recv");
    2389                 return NULL;
    2390         }
    2391 
    2392         /* Allocate a new string. */
    2393         buf = PyString_FromStringAndSize((char *) 0, recvlen);
    2394         if (buf == NULL)
    2395                 return NULL;
    2396 
    2397         /* Call the guts */
    2398         outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
    2399         if (outlen < 0) {
    2400                 /* An error occurred, release the string and return an
    2401                    error. */
    2402                 Py_DECREF(buf);
    2403                 return NULL;
    2404         }
    2405         if (outlen != recvlen) {
    2406                 /* We did not read as many bytes as we anticipated, resize the
    2407                    string if possible and be succesful. */
    2408                 if (_PyString_Resize(&buf, outlen) < 0)
    2409                         /* Oopsy, not so succesful after all. */
    2410                         return NULL;
    2411         }
    2412 
    2413         return buf;
     2488    int recvlen, flags = 0;
     2489    ssize_t outlen;
     2490    PyObject *buf;
     2491
     2492    if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
     2493        return NULL;
     2494
     2495    if (recvlen < 0) {
     2496        PyErr_SetString(PyExc_ValueError,
     2497                        "negative buffersize in recv");
     2498        return NULL;
     2499    }
     2500
     2501    /* Allocate a new string. */
     2502    buf = PyString_FromStringAndSize((char *) 0, recvlen);
     2503    if (buf == NULL)
     2504        return NULL;
     2505
     2506    /* Call the guts */
     2507    outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
     2508    if (outlen < 0) {
     2509        /* An error occurred, release the string and return an
     2510           error. */
     2511        Py_DECREF(buf);
     2512        return NULL;
     2513    }
     2514    if (outlen != recvlen) {
     2515        /* We did not read as many bytes as we anticipated, resize the
     2516           string if possible and be successful. */
     2517        if (_PyString_Resize(&buf, outlen) < 0)
     2518            /* Oopsy, not so successful after all. */
     2519            return NULL;
     2520    }
     2521
     2522    return buf;
    24142523}
    24152524
     
    24282537sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
    24292538{
    2430         static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
    2431 
    2432         int recvlen = 0, flags = 0;
    2433         ssize_t readlen;
    2434         char *buf;
    2435         int buflen;
    2436 
    2437         /* Get the buffer's memory */
    2438         if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recv_into", kwlist,
    2439                                          &buf, &buflen, &recvlen, &flags))
    2440                 return NULL;
    2441         assert(buf != 0 && buflen > 0);
    2442 
    2443         if (recvlen < 0) {
    2444                 PyErr_SetString(PyExc_ValueError,
    2445                                 "negative buffersize in recv_into");
    2446                 return NULL;
    2447         }
    2448         if (recvlen == 0) {
    2449             /* If nbytes was not specified, use the buffer's length */
    2450             recvlen = buflen;
    2451         }
    2452 
    2453         /* Check if the buffer is large enough */
    2454         if (buflen < recvlen) {
    2455                 PyErr_SetString(PyExc_ValueError,
    2456                                 "buffer too small for requested bytes");
    2457                 return NULL;
    2458         }
    2459 
    2460         /* Call the guts */
    2461         readlen = sock_recv_guts(s, buf, recvlen, flags);
    2462         if (readlen < 0) {
    2463                 /* Return an error. */
    2464                 return NULL;
    2465         }
    2466 
    2467         /* Return the number of bytes read.  Note that we do not do anything
    2468            special here in the case that readlen < recvlen. */
    2469         return PyInt_FromSsize_t(readlen);
     2539    static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
     2540
     2541    int recvlen = 0, flags = 0;
     2542    ssize_t readlen;
     2543    Py_buffer buf;
     2544    Py_ssize_t buflen;
     2545
     2546    /* Get the buffer's memory */
     2547    if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist,
     2548                                     &buf, &recvlen, &flags))
     2549        return NULL;
     2550    buflen = buf.len;
     2551    assert(buf.buf != 0 && buflen > 0);
     2552
     2553    if (recvlen < 0) {
     2554        PyErr_SetString(PyExc_ValueError,
     2555                        "negative buffersize in recv_into");
     2556        goto error;
     2557    }
     2558    if (recvlen == 0) {
     2559        /* If nbytes was not specified, use the buffer's length */
     2560        recvlen = buflen;
     2561    }
     2562
     2563    /* Check if the buffer is large enough */
     2564    if (buflen < recvlen) {
     2565        PyErr_SetString(PyExc_ValueError,
     2566                        "buffer too small for requested bytes");
     2567        goto error;
     2568    }
     2569
     2570    /* Call the guts */
     2571    readlen = sock_recv_guts(s, buf.buf, recvlen, flags);
     2572    if (readlen < 0) {
     2573        /* Return an error. */
     2574        goto error;
     2575    }
     2576
     2577    PyBuffer_Release(&buf);
     2578    /* Return the number of bytes read.  Note that we do not do anything
     2579       special here in the case that readlen < recvlen. */
     2580    return PyInt_FromSsize_t(readlen);
     2581
     2582error:
     2583    PyBuffer_Release(&buf);
     2584    return NULL;
    24702585}
    24712586
     
    24842599 * into a char buffer.  If you have any inc/def ref to do to the objects that
    24852600 * contain the buffer, do it in the caller.  This function returns the number
    2486  * of bytes succesfully read.  If there was an error, it returns -1.  Note
     2601 * of bytes successfully read.  If there was an error, it returns -1.  Note
    24872602 * that it is also possible that we return a number of bytes smaller than the
    24882603 * request bytes.
     
    24932608static ssize_t
    24942609sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
    2495                    PyObject** addr)
    2496 {
    2497         sock_addr_t addrbuf;
    2498         int timeout;
    2499         ssize_t n = -1;
    2500         socklen_t addrlen;
    2501 
    2502         *addr = NULL;
    2503 
    2504         if (!getsockaddrlen(s, &addrlen))
    2505                 return -1;
    2506 
    2507         if (!IS_SELECTABLE(s)) {
    2508                 select_error();
    2509                 return -1;
    2510         }
    2511 
    2512         Py_BEGIN_ALLOW_THREADS
    2513         memset(&addrbuf, 0, addrlen);
    2514         timeout = internal_select(s, 0);
    2515         if (!timeout) {
     2610                   PyObject** addr)
     2611{
     2612    sock_addr_t addrbuf;
     2613    int timeout;
     2614    ssize_t n = -1;
     2615    socklen_t addrlen;
     2616
     2617    *addr = NULL;
     2618
     2619    if (!getsockaddrlen(s, &addrlen))
     2620        return -1;
     2621
     2622    if (!IS_SELECTABLE(s)) {
     2623        select_error();
     2624        return -1;
     2625    }
     2626
     2627    BEGIN_SELECT_LOOP(s)
     2628    Py_BEGIN_ALLOW_THREADS
     2629    memset(&addrbuf, 0, addrlen);
     2630    timeout = internal_select_ex(s, 0, interval);
     2631    if (!timeout) {
    25162632#ifndef MS_WINDOWS
    25172633#if defined(PYOS_OS2) && !defined(PYCC_GCC)
    2518                 n = recvfrom(s->sock_fd, cbuf, len, flags,
    2519                              SAS2SA(&addrbuf), &addrlen);
    2520 #else
    2521                 n = recvfrom(s->sock_fd, cbuf, len, flags,
    2522                              (void *) &addrbuf, &addrlen);
    2523 #endif
    2524 #else
    2525                 n = recvfrom(s->sock_fd, cbuf, len, flags,
    2526                              SAS2SA(&addrbuf), &addrlen);
    2527 #endif
    2528         }
    2529         Py_END_ALLOW_THREADS
    2530 
    2531         if (timeout == 1) {
    2532                 PyErr_SetString(socket_timeout, "timed out");
    2533                 return -1;
    2534         }
    2535         if (n < 0) {
    2536                 s->errorhandler();
    2537                 return -1;
    2538         }
    2539 
    2540         if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
    2541                                    addrlen, s->sock_proto)))
    2542                 return -1;
    2543 
    2544         return n;
     2634        n = recvfrom(s->sock_fd, cbuf, len, flags,
     2635                     SAS2SA(&addrbuf), &addrlen);
     2636#else
     2637        n = recvfrom(s->sock_fd, cbuf, len, flags,
     2638                     (void *) &addrbuf, &addrlen);
     2639#endif
     2640#else
     2641        n = recvfrom(s->sock_fd, cbuf, len, flags,
     2642                     SAS2SA(&addrbuf), &addrlen);
     2643#endif
     2644    }
     2645    Py_END_ALLOW_THREADS
     2646
     2647    if (timeout == 1) {
     2648        PyErr_SetString(socket_timeout, "timed out");
     2649        return -1;
     2650    }
     2651    END_SELECT_LOOP(s)
     2652    if (n < 0) {
     2653        s->errorhandler();
     2654        return -1;
     2655    }
     2656
     2657    if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
     2658                               addrlen, s->sock_proto)))
     2659        return -1;
     2660
     2661    return n;
    25452662}
    25462663
     
    25502667sock_recvfrom(PySocketSockObject *s, PyObject *args)
    25512668{
    2552         PyObject *buf = NULL;
    2553         PyObject *addr = NULL;
    2554         PyObject *ret = NULL;
    2555         int recvlen, flags = 0;
    2556         ssize_t outlen;
    2557 
    2558         if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
    2559                 return NULL;
    2560 
    2561         if (recvlen < 0) {
    2562                 PyErr_SetString(PyExc_ValueError,
    2563                                 "negative buffersize in recvfrom");
    2564                 return NULL;
    2565         }
    2566 
    2567         buf = PyString_FromStringAndSize((char *) 0, recvlen);
    2568         if (buf == NULL)
    2569                 return NULL;
    2570 
    2571         outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
    2572                                     recvlen, flags, &addr);
    2573         if (outlen < 0) {
    2574                 goto finally;
    2575         }
    2576 
    2577         if (outlen != recvlen) {
    2578                 /* We did not read as many bytes as we anticipated, resize the
    2579                    string if possible and be succesful. */
    2580                 if (_PyString_Resize(&buf, outlen) < 0)
    2581                         /* Oopsy, not so succesful after all. */
    2582                         goto finally;
    2583         }
    2584 
    2585         ret = PyTuple_Pack(2, buf, addr);
     2669    PyObject *buf = NULL;
     2670    PyObject *addr = NULL;
     2671    PyObject *ret = NULL;
     2672    int recvlen, flags = 0;
     2673    ssize_t outlen;
     2674
     2675    if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
     2676        return NULL;
     2677
     2678    if (recvlen < 0) {
     2679        PyErr_SetString(PyExc_ValueError,
     2680                        "negative buffersize in recvfrom");
     2681        return NULL;
     2682    }
     2683
     2684    buf = PyString_FromStringAndSize((char *) 0, recvlen);
     2685    if (buf == NULL)
     2686        return NULL;
     2687
     2688    outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
     2689                                recvlen, flags, &addr);
     2690    if (outlen < 0) {
     2691        goto finally;
     2692    }
     2693
     2694    if (outlen != recvlen) {
     2695        /* We did not read as many bytes as we anticipated, resize the
     2696           string if possible and be successful. */
     2697        if (_PyString_Resize(&buf, outlen) < 0)
     2698            /* Oopsy, not so successful after all. */
     2699            goto finally;
     2700    }
     2701
     2702    ret = PyTuple_Pack(2, buf, addr);
    25862703
    25872704finally:
    2588         Py_XDECREF(buf);
    2589         Py_XDECREF(addr);
    2590         return ret;
     2705    Py_XDECREF(buf);
     2706    Py_XDECREF(addr);
     2707    return ret;
    25912708}
    25922709
     
    26022719sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
    26032720{
    2604         static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
    2605 
    2606         int recvlen = 0, flags = 0;
    2607         ssize_t readlen;
    2608         char *buf;
    2609         int buflen;
    2610 
    2611         PyObject *addr = NULL;
    2612 
    2613         if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recvfrom_into",
    2614                                          kwlist, &buf, &buflen,
    2615                                          &recvlen, &flags))
    2616                 return NULL;
    2617         assert(buf != 0 && buflen > 0);
    2618 
    2619         if (recvlen < 0) {
    2620                 PyErr_SetString(PyExc_ValueError,
    2621                                 "negative buffersize in recvfrom_into");
    2622                 return NULL;
    2623         }
    2624         if (recvlen == 0) {
    2625             /* If nbytes was not specified, use the buffer's length */
    2626             recvlen = buflen;
    2627         }
    2628 
    2629         readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
    2630         if (readlen < 0) {
    2631                 /* Return an error */
    2632                 Py_XDECREF(addr);
    2633                 return NULL;
    2634         }
    2635 
    2636         /* Return the number of bytes read and the address.  Note that we do
    2637            not do anything special here in the case that readlen < recvlen. */
    2638         return Py_BuildValue("lN", readlen, addr);
     2721    static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
     2722
     2723    int recvlen = 0, flags = 0;
     2724    ssize_t readlen;
     2725    Py_buffer buf;
     2726    int buflen;
     2727
     2728    PyObject *addr = NULL;
     2729
     2730    if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into",
     2731                                     kwlist, &buf,
     2732                                     &recvlen, &flags))
     2733        return NULL;
     2734    buflen = buf.len;
     2735    assert(buf.buf != 0 && buflen > 0);
     2736
     2737    if (recvlen < 0) {
     2738        PyErr_SetString(PyExc_ValueError,
     2739                        "negative buffersize in recvfrom_into");
     2740        goto error;
     2741    }
     2742    if (recvlen == 0) {
     2743        /* If nbytes was not specified, use the buffer's length */
     2744        recvlen = buflen;
     2745    }
     2746
     2747    readlen = sock_recvfrom_guts(s, buf.buf, recvlen, flags, &addr);
     2748    if (readlen < 0) {
     2749        /* Return an error */
     2750        goto error;
     2751    }
     2752
     2753    PyBuffer_Release(&buf);
     2754    /* Return the number of bytes read and the address.  Note that we do
     2755       not do anything special here in the case that readlen < recvlen. */
     2756    return Py_BuildValue("lN", readlen, addr);
     2757
     2758error:
     2759    Py_XDECREF(addr);
     2760    PyBuffer_Release(&buf);
     2761    return NULL;
    26392762}
    26402763
     
    26502773sock_send(PySocketSockObject *s, PyObject *args)
    26512774{
    2652         char *buf;
    2653         int len, n = -1, flags = 0, timeout;
    2654         Py_buffer pbuf;
    2655 
    2656         if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
    2657                 return NULL;
    2658 
    2659         if (!IS_SELECTABLE(s)) {
    2660                 PyBuffer_Release(&pbuf);
    2661                 return select_error();
    2662         }
    2663         buf = pbuf.buf;
    2664         len = pbuf.len;
    2665 
    2666         Py_BEGIN_ALLOW_THREADS
    2667         timeout = internal_select(s, 1);
    2668         if (!timeout)
     2775    char *buf;
     2776    int len, n = -1, flags = 0, timeout;
     2777    Py_buffer pbuf;
     2778
     2779    if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
     2780        return NULL;
     2781
     2782    if (!IS_SELECTABLE(s)) {
     2783        PyBuffer_Release(&pbuf);
     2784        return select_error();
     2785    }
     2786    buf = pbuf.buf;
     2787    len = pbuf.len;
     2788
     2789    BEGIN_SELECT_LOOP(s)
     2790    Py_BEGIN_ALLOW_THREADS
     2791    timeout = internal_select_ex(s, 1, interval);
     2792    if (!timeout)
    26692793#ifdef __VMS
    2670                 n = sendsegmented(s->sock_fd, buf, len, flags);
    2671 #else
    2672                 n = send(s->sock_fd, buf, len, flags);
    2673 #endif
    2674         Py_END_ALLOW_THREADS
    2675 
    2676         PyBuffer_Release(&pbuf);
    2677 
    2678         if (timeout == 1) {
    2679                 PyErr_SetString(socket_timeout, "timed out");
    2680                 return NULL;
    2681         }
    2682         if (n < 0)
    2683                 return s->errorhandler();
    2684         return PyInt_FromLong((long)n);
     2794        n = sendsegmented(s->sock_fd, buf, len, flags);
     2795#else
     2796        n = send(s->sock_fd, buf, len, flags);
     2797#endif
     2798    Py_END_ALLOW_THREADS
     2799    if (timeout == 1) {
     2800        PyBuffer_Release(&pbuf);
     2801        PyErr_SetString(socket_timeout, "timed out");
     2802        return NULL;
     2803    }
     2804    END_SELECT_LOOP(s)
     2805
     2806    PyBuffer_Release(&pbuf);
     2807    if (n < 0)
     2808        return s->errorhandler();
     2809    return PyInt_FromLong((long)n);
    26852810}
    26862811
     
    26982823sock_sendall(PySocketSockObject *s, PyObject *args)
    26992824{
    2700         char *buf;
    2701         int len, n = -1, flags = 0, timeout;
    2702         Py_buffer pbuf;
    2703 
    2704         if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
    2705                 return NULL;
    2706         buf = pbuf.buf;
    2707         len = pbuf.len;
    2708 
    2709         if (!IS_SELECTABLE(s)) {
    2710                 PyBuffer_Release(&pbuf);
    2711                 return select_error();
    2712         }
    2713 
    2714         Py_BEGIN_ALLOW_THREADS
    2715         do {
    2716                 timeout = internal_select(s, 1);
    2717                 n = -1;
    2718                 if (timeout)
    2719                         break;
     2825    char *buf;
     2826    int len, n = -1, flags = 0, timeout, saved_errno;
     2827    Py_buffer pbuf;
     2828
     2829    if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
     2830        return NULL;
     2831    buf = pbuf.buf;
     2832    len = pbuf.len;
     2833
     2834    if (!IS_SELECTABLE(s)) {
     2835        PyBuffer_Release(&pbuf);
     2836        return select_error();
     2837    }
     2838
     2839    do {
     2840        BEGIN_SELECT_LOOP(s)
     2841        Py_BEGIN_ALLOW_THREADS
     2842        timeout = internal_select_ex(s, 1, interval);
     2843        n = -1;
     2844        if (!timeout) {
    27202845#ifdef __VMS
    2721                 n = sendsegmented(s->sock_fd, buf, len, flags);
    2722 #else
    2723                 n = send(s->sock_fd, buf, len, flags);
    2724 #endif
    2725                 if (n < 0)
    2726                         break;
    2727                 buf += n;
    2728                 len -= n;
    2729         } while (len > 0);
    2730         Py_END_ALLOW_THREADS
    2731         PyBuffer_Release(&pbuf);
    2732 
    2733         if (timeout == 1) {
    2734                 PyErr_SetString(socket_timeout, "timed out");
    2735                 return NULL;
    2736         }
    2737         if (n < 0)
    2738                 return s->errorhandler();
    2739 
    2740         Py_INCREF(Py_None);
    2741         return Py_None;
     2846            n = sendsegmented(s->sock_fd, buf, len, flags);
     2847#else
     2848            n = send(s->sock_fd, buf, len, flags);
     2849#endif
     2850        }
     2851        Py_END_ALLOW_THREADS
     2852        if (timeout == 1) {
     2853            PyBuffer_Release(&pbuf);
     2854            PyErr_SetString(socket_timeout, "timed out");
     2855            return NULL;
     2856        }
     2857        END_SELECT_LOOP(s)
     2858        /* PyErr_CheckSignals() might change errno */
     2859        saved_errno = errno;
     2860        /* We must run our signal handlers before looping again.
     2861           send() can return a successful partial write when it is
     2862           interrupted, so we can't restrict ourselves to EINTR. */
     2863        if (PyErr_CheckSignals()) {
     2864            PyBuffer_Release(&pbuf);
     2865            return NULL;
     2866        }
     2867        if (n < 0) {
     2868            /* If interrupted, try again */
     2869            if (saved_errno == EINTR)
     2870                continue;
     2871            else
     2872                break;
     2873        }
     2874        buf += n;
     2875        len -= n;
     2876    } while (len > 0);
     2877    PyBuffer_Release(&pbuf);
     2878
     2879    if (n < 0)
     2880        return s->errorhandler();
     2881
     2882    Py_INCREF(Py_None);
     2883    return Py_None;
    27422884}
    27432885
     
    27562898sock_sendto(PySocketSockObject *s, PyObject *args)
    27572899{
    2758         Py_buffer pbuf;
    2759         PyObject *addro;
    2760         char *buf;
    2761         Py_ssize_t len;
    2762         sock_addr_t addrbuf;
    2763         int addrlen, n = -1, flags, timeout;
    2764 
    2765         flags = 0;
    2766         if (!PyArg_ParseTuple(args, "s*O:sendto", &pbuf, &addro)) {
    2767                 PyErr_Clear();
    2768                 if (!PyArg_ParseTuple(args, "s*iO:sendto",
    2769                                       &pbuf, &flags, &addro))
    2770                         return NULL;
    2771         }
    2772         buf = pbuf.buf;
    2773         len = pbuf.len;
    2774 
    2775         if (!IS_SELECTABLE(s)) {
    2776                 PyBuffer_Release(&pbuf);
    2777                 return select_error();
    2778         }
    2779 
    2780         if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) {
    2781                 PyBuffer_Release(&pbuf);
    2782                 return NULL;
    2783         }
    2784 
    2785         Py_BEGIN_ALLOW_THREADS
    2786         timeout = internal_select(s, 1);
    2787         if (!timeout)
    2788                 n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
    2789         Py_END_ALLOW_THREADS
    2790 
    2791         PyBuffer_Release(&pbuf);
    2792         if (timeout == 1) {
    2793                 PyErr_SetString(socket_timeout, "timed out");
    2794                 return NULL;
    2795         }
    2796         if (n < 0)
    2797                 return s->errorhandler();
    2798         return PyInt_FromLong((long)n);
     2900    Py_buffer pbuf;
     2901    PyObject *addro;
     2902    char *buf;
     2903    Py_ssize_t len;
     2904    sock_addr_t addrbuf;
     2905    int addrlen, n = -1, flags, timeout;
     2906    int arglen;
     2907
     2908    flags = 0;
     2909    arglen = PyTuple_Size(args);
     2910    switch(arglen) {
     2911        case 2:
     2912            PyArg_ParseTuple(args, "s*O:sendto", &pbuf, &addro);
     2913            break;
     2914        case 3:
     2915            PyArg_ParseTuple(args, "s*iO:sendto", &pbuf, &flags, &addro);
     2916            break;
     2917        default:
     2918            PyErr_Format(PyExc_TypeError, "sendto() takes 2 or 3"
     2919                         " arguments (%d given)", arglen);
     2920    }
     2921    if (PyErr_Occurred())
     2922        return NULL;
     2923
     2924    buf = pbuf.buf;
     2925    len = pbuf.len;
     2926
     2927    if (!IS_SELECTABLE(s)) {
     2928        PyBuffer_Release(&pbuf);
     2929        return select_error();
     2930    }
     2931
     2932    if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) {
     2933        PyBuffer_Release(&pbuf);
     2934        return NULL;
     2935    }
     2936
     2937    BEGIN_SELECT_LOOP(s)
     2938    Py_BEGIN_ALLOW_THREADS
     2939    timeout = internal_select_ex(s, 1, interval);
     2940    if (!timeout)
     2941        n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
     2942    Py_END_ALLOW_THREADS
     2943
     2944    if (timeout == 1) {
     2945        PyBuffer_Release(&pbuf);
     2946        PyErr_SetString(socket_timeout, "timed out");
     2947        return NULL;
     2948    }
     2949    END_SELECT_LOOP(s)
     2950    PyBuffer_Release(&pbuf);
     2951    if (n < 0)
     2952        return s->errorhandler();
     2953    return PyInt_FromLong((long)n);
    27992954}
    28002955
     
    28112966sock_shutdown(PySocketSockObject *s, PyObject *arg)
    28122967{
    2813         int how;
    2814         int res;
    2815 
    2816         how = PyInt_AsLong(arg);
    2817         if (how == -1 && PyErr_Occurred())
    2818                 return NULL;
    2819         Py_BEGIN_ALLOW_THREADS
    2820         res = shutdown(s->sock_fd, how);
    2821         Py_END_ALLOW_THREADS
    2822         if (res < 0)
    2823                 return s->errorhandler();
    2824         Py_INCREF(Py_None);
    2825         return Py_None;
     2968    int how;
     2969    int res;
     2970
     2971    how = _PyInt_AsInt(arg);
     2972    if (how == -1 && PyErr_Occurred())
     2973        return NULL;
     2974    Py_BEGIN_ALLOW_THREADS
     2975    res = shutdown(s->sock_fd, how);
     2976    Py_END_ALLOW_THREADS
     2977    if (res < 0)
     2978        return s->errorhandler();
     2979    Py_INCREF(Py_None);
     2980    return Py_None;
    28262981}
    28272982
     
    28362991sock_ioctl(PySocketSockObject *s, PyObject *arg)
    28372992{
    2838         unsigned long cmd = SIO_RCVALL;
    2839         unsigned int option = RCVALL_ON;
    2840         DWORD recv;
    2841 
    2842         if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
    2843                 return NULL;
    2844 
    2845         if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
    2846                      NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
    2847                 return set_error();
    2848         }
    2849         return PyLong_FromUnsignedLong(recv);
     2993    unsigned long cmd = SIO_RCVALL;
     2994    PyObject *argO;
     2995    DWORD recv;
     2996
     2997    if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
     2998        return NULL;
     2999
     3000    switch (cmd) {
     3001    case SIO_RCVALL: {
     3002        unsigned int option = RCVALL_ON;
     3003        if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
     3004            return NULL;
     3005        if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
     3006                         NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
     3007            return set_error();
     3008        }
     3009        return PyLong_FromUnsignedLong(recv); }
     3010    case SIO_KEEPALIVE_VALS: {
     3011        struct tcp_keepalive ka;
     3012        if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
     3013                        &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
     3014            return NULL;
     3015        if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
     3016                         NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
     3017            return set_error();
     3018        }
     3019        return PyLong_FromUnsignedLong(recv); }
     3020    default:
     3021        PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd);
     3022        return NULL;
     3023    }
    28503024}
    28513025PyDoc_STRVAR(sock_ioctl_doc,
    28523026"ioctl(cmd, option) -> long\n\
    28533027\n\
    2854 Control the socket with WSAIoctl syscall. Currently only socket.SIO_RCVALL\n\
    2855 is supported as control. Options must be one of the socket.RCVALL_*\n\
    2856 constants.");
     3028Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
     3029SIO_RCVALL:  'option' must be one of the socket.RCVALL_* constants.\n\
     3030SIO_KEEPALIVE_VALS:  'option' is a tuple of (onoff, timeout, interval).");
    28573031
    28583032#endif
     
    28613035
    28623036static PyMethodDef sock_methods[] = {
    2863         {"accept",        (PyCFunction)sock_accept, METH_NOARGS,
    2864                           accept_doc},
    2865         {"bind",          (PyCFunction)sock_bind, METH_O,
    2866                           bind_doc},
    2867         {"close",         (PyCFunction)sock_close, METH_NOARGS,
    2868                           close_doc},
    2869         {"connect",       (PyCFunction)sock_connect, METH_O,
    2870                           connect_doc},
    2871         {"connect_ex",    (PyCFunction)sock_connect_ex, METH_O,
    2872                           connect_ex_doc},
     3037    {"accept",            (PyCFunction)sock_accept, METH_NOARGS,
     3038                      accept_doc},
     3039    {"bind",              (PyCFunction)sock_bind, METH_O,
     3040                      bind_doc},
     3041    {"close",             (PyCFunction)sock_close, METH_NOARGS,
     3042                      close_doc},
     3043    {"connect",           (PyCFunction)sock_connect, METH_O,
     3044                      connect_doc},
     3045    {"connect_ex",        (PyCFunction)sock_connect_ex, METH_O,
     3046                      connect_ex_doc},
    28733047#ifndef NO_DUP
    2874         {"dup",           (PyCFunction)sock_dup, METH_NOARGS,
    2875                           dup_doc},
    2876 #endif
    2877         {"fileno",        (PyCFunction)sock_fileno, METH_NOARGS,
    2878                           fileno_doc},
     3048    {"dup",               (PyCFunction)sock_dup, METH_NOARGS,
     3049                      dup_doc},
     3050#endif
     3051    {"fileno",            (PyCFunction)sock_fileno, METH_NOARGS,
     3052                      fileno_doc},
    28793053#ifdef HAVE_GETPEERNAME
    2880         {"getpeername",   (PyCFunction)sock_getpeername,
    2881                           METH_NOARGS, getpeername_doc},
    2882 #endif
    2883         {"getsockname",   (PyCFunction)sock_getsockname,
    2884                           METH_NOARGS, getsockname_doc},
    2885         {"getsockopt",    (PyCFunction)sock_getsockopt, METH_VARARGS,
    2886                           getsockopt_doc},
     3054    {"getpeername",       (PyCFunction)sock_getpeername,
     3055                      METH_NOARGS, getpeername_doc},
     3056#endif
     3057    {"getsockname",       (PyCFunction)sock_getsockname,
     3058                      METH_NOARGS, getsockname_doc},
     3059    {"getsockopt",        (PyCFunction)sock_getsockopt, METH_VARARGS,
     3060                      getsockopt_doc},
    28873061#if defined(MS_WINDOWS) && defined(SIO_RCVALL)
    2888         {"ioctl",         (PyCFunction)sock_ioctl, METH_VARARGS,
    2889                           sock_ioctl_doc},
    2890 #endif
    2891         {"listen",        (PyCFunction)sock_listen, METH_O,
    2892                           listen_doc},
     3062    {"ioctl",             (PyCFunction)sock_ioctl, METH_VARARGS,
     3063                      sock_ioctl_doc},
     3064#endif
     3065    {"listen",            (PyCFunction)sock_listen, METH_O,
     3066                      listen_doc},
    28933067#ifndef NO_DUP
    2894         {"makefile",      (PyCFunction)sock_makefile, METH_VARARGS,
    2895                           makefile_doc},
    2896 #endif
    2897         {"recv",          (PyCFunction)sock_recv, METH_VARARGS,
    2898                           recv_doc},
    2899         {"recv_into",     (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
    2900                           recv_into_doc},
    2901         {"recvfrom",      (PyCFunction)sock_recvfrom, METH_VARARGS,
    2902                           recvfrom_doc},
    2903         {"recvfrom_into",  (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
    2904                           recvfrom_into_doc},
    2905         {"send",          (PyCFunction)sock_send, METH_VARARGS,
    2906                           send_doc},
    2907         {"sendall",       (PyCFunction)sock_sendall, METH_VARARGS,
    2908                           sendall_doc},
    2909         {"sendto",        (PyCFunction)sock_sendto, METH_VARARGS,
    2910                           sendto_doc},
    2911         {"setblocking",   (PyCFunction)sock_setblocking, METH_O,
    2912                           setblocking_doc},
    2913         {"settimeout",    (PyCFunction)sock_settimeout, METH_O,
    2914                           settimeout_doc},
    2915         {"gettimeout",    (PyCFunction)sock_gettimeout, METH_NOARGS,
    2916                           gettimeout_doc},
    2917         {"setsockopt",    (PyCFunction)sock_setsockopt, METH_VARARGS,
    2918                           setsockopt_doc},
    2919         {"shutdown",      (PyCFunction)sock_shutdown, METH_O,
    2920                           shutdown_doc},
     3068    {"makefile",          (PyCFunction)sock_makefile, METH_VARARGS,
     3069                      makefile_doc},
     3070#endif
     3071    {"recv",              (PyCFunction)sock_recv, METH_VARARGS,
     3072                      recv_doc},
     3073    {"recv_into",         (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
     3074                      recv_into_doc},
     3075    {"recvfrom",          (PyCFunction)sock_recvfrom, METH_VARARGS,
     3076                      recvfrom_doc},
     3077    {"recvfrom_into",  (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
     3078                      recvfrom_into_doc},
     3079    {"send",              (PyCFunction)sock_send, METH_VARARGS,
     3080                      send_doc},
     3081    {"sendall",           (PyCFunction)sock_sendall, METH_VARARGS,
     3082                      sendall_doc},
     3083    {"sendto",            (PyCFunction)sock_sendto, METH_VARARGS,
     3084                      sendto_doc},
     3085    {"setblocking",       (PyCFunction)sock_setblocking, METH_O,
     3086                      setblocking_doc},
     3087    {"settimeout",    (PyCFunction)sock_settimeout, METH_O,
     3088                      settimeout_doc},
     3089    {"gettimeout",    (PyCFunction)sock_gettimeout, METH_NOARGS,
     3090                      gettimeout_doc},
     3091    {"setsockopt",        (PyCFunction)sock_setsockopt, METH_VARARGS,
     3092                      setsockopt_doc},
     3093    {"shutdown",          (PyCFunction)sock_shutdown, METH_O,
     3094                      shutdown_doc},
    29213095#ifdef RISCOS
    2922         {"sleeptaskw",    (PyCFunction)sock_sleeptaskw, METH_O,
    2923                           sleeptaskw_doc},
    2924 #endif
    2925         {NULL,                  NULL}           /* sentinel */
     3096    {"sleeptaskw",        (PyCFunction)sock_sleeptaskw, METH_O,
     3097                      sleeptaskw_doc},
     3098#endif
     3099    {NULL,                      NULL}           /* sentinel */
    29263100};
    29273101
     
    29413115sock_dealloc(PySocketSockObject *s)
    29423116{
    2943         if (s->sock_fd != -1)
    2944                 (void) SOCKETCLOSE(s->sock_fd);
    2945         Py_TYPE(s)->tp_free((PyObject *)s);
     3117    if (s->sock_fd != -1)
     3118        (void) SOCKETCLOSE(s->sock_fd);
     3119    Py_TYPE(s)->tp_free((PyObject *)s);
    29463120}
    29473121
     
    29503124sock_repr(PySocketSockObject *s)
    29513125{
    2952         char buf[512];
     3126    char buf[512];
    29533127#if SIZEOF_SOCKET_T > SIZEOF_LONG
    2954         if (s->sock_fd > LONG_MAX) {
    2955                 /* this can occur on Win64, and actually there is a special
    2956                    ugly printf formatter for decimal pointer length integer
    2957                    printing, only bother if necessary*/
    2958                 PyErr_SetString(PyExc_OverflowError,
    2959                                 "no printf formatter to display "
    2960                                 "the socket descriptor in decimal");
    2961                 return NULL;
    2962         }
    2963 #endif
    2964         PyOS_snprintf(
    2965                 buf, sizeof(buf),
    2966                 "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
    2967                 (long)s->sock_fd, s->sock_family,
    2968                 s->sock_type,
    2969                 s->sock_proto);
    2970         return PyString_FromString(buf);
     3128    if (s->sock_fd > LONG_MAX) {
     3129        /* this can occur on Win64, and actually there is a special
     3130           ugly printf formatter for decimal pointer length integer
     3131           printing, only bother if necessary*/
     3132        PyErr_SetString(PyExc_OverflowError,
     3133                        "no printf formatter to display "
     3134                        "the socket descriptor in decimal");
     3135        return NULL;
     3136    }
     3137#endif
     3138    PyOS_snprintf(
     3139        buf, sizeof(buf),
     3140        "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
     3141        (long)s->sock_fd, s->sock_family,
     3142        s->sock_type,
     3143        s->sock_proto);
     3144    return PyString_FromString(buf);
    29713145}
    29723146
     
    29773151sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    29783152{
    2979         PyObject *new;
    2980 
    2981         new = type->tp_alloc(type, 0);
    2982         if (new != NULL) {
    2983                 ((PySocketSockObject *)new)->sock_fd = -1;
    2984                 ((PySocketSockObject *)new)->sock_timeout = -1.0;
    2985                 ((PySocketSockObject *)new)->errorhandler = &set_error;
    2986         }
    2987         return new;
     3153    PyObject *new;
     3154
     3155    new = type->tp_alloc(type, 0);
     3156    if (new != NULL) {
     3157        ((PySocketSockObject *)new)->sock_fd = -1;
     3158        ((PySocketSockObject *)new)->sock_timeout = -1.0;
     3159        ((PySocketSockObject *)new)->errorhandler = &set_error;
     3160    }
     3161    return new;
    29883162}
    29893163
     
    29953169sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
    29963170{
    2997         PySocketSockObject *s = (PySocketSockObject *)self;
    2998         SOCKET_T fd;
    2999         int family = AF_INET, type = SOCK_STREAM, proto = 0;
    3000         static char *keywords[] = {"family", "type", "proto", 0};
    3001 
    3002         if (!PyArg_ParseTupleAndKeywords(args, kwds,
    3003                                         "|iii:socket", keywords,
    3004                                         &family, &type, &proto))
    3005                 return -1;
    3006 
    3007         Py_BEGIN_ALLOW_THREADS
    3008         fd = socket(family, type, proto);
    3009         Py_END_ALLOW_THREADS
     3171    PySocketSockObject *s = (PySocketSockObject *)self;
     3172    SOCKET_T fd;
     3173    int family = AF_INET, type = SOCK_STREAM, proto = 0;
     3174    static char *keywords[] = {"family", "type", "proto", 0};
     3175
     3176    if (!PyArg_ParseTupleAndKeywords(args, kwds,
     3177                                    "|iii:socket", keywords,
     3178                                    &family, &type, &proto))
     3179        return -1;
     3180
     3181    Py_BEGIN_ALLOW_THREADS
     3182    fd = socket(family, type, proto);
     3183    Py_END_ALLOW_THREADS
    30103184
    30113185#ifdef MS_WINDOWS
    3012         if (fd == INVALID_SOCKET)
    3013 #else
    3014         if (fd < 0)
    3015 #endif
    3016         {
    3017                 set_error();
    3018                 return -1;
    3019         }
    3020         init_sockobject(s, fd, family, type, proto);
    3021 
    3022         return 0;
     3186    if (fd == INVALID_SOCKET)
     3187#else
     3188    if (fd < 0)
     3189#endif
     3190    {
     3191        set_error();
     3192        return -1;
     3193    }
     3194    init_sockobject(s, fd, family, type, proto);
     3195
     3196    return 0;
    30233197
    30243198}
     
    30283202
    30293203static PyTypeObject sock_type = {
    3030         PyVarObject_HEAD_INIT(0, 0)     /* Must fill in type value later */
    3031         "_socket.socket",                       /* tp_name */
    3032         sizeof(PySocketSockObject),             /* tp_basicsize */
    3033         0,                                      /* tp_itemsize */
    3034         (destructor)sock_dealloc,               /* tp_dealloc */
    3035         0,                                      /* tp_print */
    3036         0,                                      /* tp_getattr */
    3037         0,                                      /* tp_setattr */
    3038         0,                                      /* tp_compare */
    3039         (reprfunc)sock_repr,                    /* tp_repr */
    3040         0,                                      /* tp_as_number */
    3041         0,                                      /* tp_as_sequence */
    3042         0,                                      /* tp_as_mapping */
    3043         0,                                      /* tp_hash */
    3044         0,                                      /* tp_call */
    3045         0,                                      /* tp_str */
    3046         PyObject_GenericGetAttr,                /* tp_getattro */
    3047         0,                                      /* tp_setattro */
    3048         0,                                      /* tp_as_buffer */
    3049         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
    3050         sock_doc,                               /* tp_doc */
    3051         0,                                      /* tp_traverse */
    3052         0,                                      /* tp_clear */
    3053         0,                                      /* tp_richcompare */
    3054         0,                                      /* tp_weaklistoffset */
    3055         0,                                      /* tp_iter */
    3056         0,                                      /* tp_iternext */
    3057         sock_methods,                           /* tp_methods */
    3058         sock_memberlist,                        /* tp_members */
    3059         0,                                      /* tp_getset */
    3060         0,                                      /* tp_base */
    3061         0,                                      /* tp_dict */
    3062         0,                                      /* tp_descr_get */
    3063         0,                                      /* tp_descr_set */
    3064         0,                                      /* tp_dictoffset */
    3065         sock_initobj,                           /* tp_init */
    3066         PyType_GenericAlloc,                    /* tp_alloc */
    3067         sock_new,                               /* tp_new */
    3068         PyObject_Del,                           /* tp_free */
     3204    PyVarObject_HEAD_INIT(0, 0)         /* Must fill in type value later */
     3205    "_socket.socket",                           /* tp_name */
     3206    sizeof(PySocketSockObject),                 /* tp_basicsize */
     3207    0,                                          /* tp_itemsize */
     3208    (destructor)sock_dealloc,                   /* tp_dealloc */
     3209    0,                                          /* tp_print */
     3210    0,                                          /* tp_getattr */
     3211    0,                                          /* tp_setattr */
     3212    0,                                          /* tp_compare */
     3213    (reprfunc)sock_repr,                        /* tp_repr */
     3214    0,                                          /* tp_as_number */
     3215    0,                                          /* tp_as_sequence */
     3216    0,                                          /* tp_as_mapping */
     3217    0,                                          /* tp_hash */
     3218    0,                                          /* tp_call */
     3219    0,                                          /* tp_str */
     3220    PyObject_GenericGetAttr,                    /* tp_getattro */
     3221    0,                                          /* tp_setattro */
     3222    0,                                          /* tp_as_buffer */
     3223    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
     3224    sock_doc,                                   /* tp_doc */
     3225    0,                                          /* tp_traverse */
     3226    0,                                          /* tp_clear */
     3227    0,                                          /* tp_richcompare */
     3228    0,                                          /* tp_weaklistoffset */
     3229    0,                                          /* tp_iter */
     3230    0,                                          /* tp_iternext */
     3231    sock_methods,                               /* tp_methods */
     3232    sock_memberlist,                            /* tp_members */
     3233    0,                                          /* tp_getset */
     3234    0,                                          /* tp_base */
     3235    0,                                          /* tp_dict */
     3236    0,                                          /* tp_descr_get */
     3237    0,                                          /* tp_descr_set */
     3238    0,                                          /* tp_dictoffset */
     3239    sock_initobj,                               /* tp_init */
     3240    PyType_GenericAlloc,                        /* tp_alloc */
     3241    sock_new,                                   /* tp_new */
     3242    PyObject_Del,                               /* tp_free */
    30693243};
    30703244
     
    30763250socket_gethostname(PyObject *self, PyObject *unused)
    30773251{
    3078         char buf[1024];
    3079         int res;
    3080         Py_BEGIN_ALLOW_THREADS
    3081         res = gethostname(buf, (int) sizeof buf - 1);
    3082         Py_END_ALLOW_THREADS
    3083         if (res < 0)
    3084                 return set_error();
    3085         buf[sizeof buf - 1] = '\0';
    3086         return PyString_FromString(buf);
     3252    char buf[1024];
     3253    int res;
     3254    Py_BEGIN_ALLOW_THREADS
     3255    res = gethostname(buf, (int) sizeof buf - 1);
     3256    Py_END_ALLOW_THREADS
     3257    if (res < 0)
     3258        return set_error();
     3259    buf[sizeof buf - 1] = '\0';
     3260    return PyString_FromString(buf);
    30873261}
    30883262
     
    30993273socket_gethostbyname(PyObject *self, PyObject *args)
    31003274{
    3101         char *name;
    3102         sock_addr_t addrbuf;
    3103 
    3104         if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
    3105                 return NULL;
    3106         if (setipaddr(name, SAS2SA(&addrbuf),  sizeof(addrbuf), AF_INET) < 0)
    3107                 return NULL;
    3108         return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
     3275    char *name;
     3276    sock_addr_t addrbuf;
     3277
     3278    if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
     3279        return NULL;
     3280    if (setipaddr(name, SAS2SA(&addrbuf),  sizeof(addrbuf), AF_INET) < 0)
     3281        return NULL;
     3282    return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
    31093283}
    31103284
     
    31203294gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
    31213295{
    3122         char **pch;
    3123         PyObject *rtn_tuple = (PyObject *)NULL;
    3124         PyObject *name_list = (PyObject *)NULL;
    3125         PyObject *addr_list = (PyObject *)NULL;
    3126         PyObject *tmp;
    3127 
    3128         if (h == NULL) {
    3129                 /* Let's get real error message to return */
     3296    char **pch;
     3297    PyObject *rtn_tuple = (PyObject *)NULL;
     3298    PyObject *name_list = (PyObject *)NULL;
     3299    PyObject *addr_list = (PyObject *)NULL;
     3300    PyObject *tmp;
     3301
     3302    if (h == NULL) {
     3303        /* Let's get real error message to return */
    31303304#ifndef RISCOS
    3131                 set_herror(h_errno);
    3132 #else
    3133                 PyErr_SetString(socket_error, "host not found");
    3134 #endif
    3135                 return NULL;
    3136         }
    3137 
    3138         if (h->h_addrtype != af) {
    3139                 /* Let's get real error message to return */
    3140                 PyErr_SetString(socket_error,
    3141                                 (char *)strerror(EAFNOSUPPORT));
    3142 
    3143                 return NULL;
    3144         }
    3145 
    3146         switch (af) {
    3147 
    3148         case AF_INET:
    3149                 if (alen < sizeof(struct sockaddr_in))
    3150                         return NULL;
    3151                 break;
     3305        set_herror(h_errno);
     3306#else
     3307        PyErr_SetString(socket_error, "host not found");
     3308#endif
     3309        return NULL;
     3310    }
     3311
     3312    if (h->h_addrtype != af) {
     3313        /* Let's get real error message to return */
     3314        PyErr_SetString(socket_error,
     3315                        (char *)strerror(EAFNOSUPPORT));
     3316
     3317        return NULL;
     3318    }
     3319
     3320    switch (af) {
     3321
     3322    case AF_INET:
     3323        if (alen < sizeof(struct sockaddr_in))
     3324            return NULL;
     3325        break;
    31523326
    31533327#ifdef ENABLE_IPV6
    3154         case AF_INET6:
    3155                 if (alen < sizeof(struct sockaddr_in6))
    3156                         return NULL;
    3157                 break;
    3158 #endif
    3159 
    3160         }
    3161 
    3162         if ((name_list = PyList_New(0)) == NULL)
    3163                 goto err;
    3164 
    3165         if ((addr_list = PyList_New(0)) == NULL)
    3166                 goto err;
    3167 
    3168         /* SF #1511317: h_aliases can be NULL */
    3169         if (h->h_aliases) {
    3170                 for (pch = h->h_aliases; *pch != NULL; pch++) {
    3171                         int status;
    3172                         tmp = PyString_FromString(*pch);
    3173                         if (tmp == NULL)
    3174                                 goto err;
    3175 
    3176                         status = PyList_Append(name_list, tmp);
    3177                         Py_DECREF(tmp);
    3178 
    3179                         if (status)
    3180                                 goto err;
    3181                 }
    3182         }
    3183 
    3184         for (pch = h->h_addr_list; *pch != NULL; pch++) {
    3185                 int status;
    3186 
    3187                 switch (af) {
    3188 
    3189                 case AF_INET:
    3190                     {
    3191                         struct sockaddr_in sin;
    3192                         memset(&sin, 0, sizeof(sin));
    3193                         sin.sin_family = af;
     3328    case AF_INET6:
     3329        if (alen < sizeof(struct sockaddr_in6))
     3330            return NULL;
     3331        break;
     3332#endif
     3333
     3334    }
     3335
     3336    if ((name_list = PyList_New(0)) == NULL)
     3337        goto err;
     3338
     3339    if ((addr_list = PyList_New(0)) == NULL)
     3340        goto err;
     3341
     3342    /* SF #1511317: h_aliases can be NULL */
     3343    if (h->h_aliases) {
     3344        for (pch = h->h_aliases; *pch != NULL; pch++) {
     3345            int status;
     3346            tmp = PyString_FromString(*pch);
     3347            if (tmp == NULL)
     3348                goto err;
     3349
     3350            status = PyList_Append(name_list, tmp);
     3351            Py_DECREF(tmp);
     3352
     3353            if (status)
     3354                goto err;
     3355        }
     3356    }
     3357
     3358    for (pch = h->h_addr_list; *pch != NULL; pch++) {
     3359        int status;
     3360
     3361        switch (af) {
     3362
     3363        case AF_INET:
     3364            {
     3365            struct sockaddr_in sin;
     3366            memset(&sin, 0, sizeof(sin));
     3367            sin.sin_family = af;
    31943368#ifdef HAVE_SOCKADDR_SA_LEN
    3195                         sin.sin_len = sizeof(sin);
    3196 #endif
    3197                         memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
    3198                         tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
    3199 
    3200                         if (pch == h->h_addr_list && alen >= sizeof(sin))
    3201                                 memcpy((char *) addr, &sin, sizeof(sin));
    3202                         break;
    3203                     }
     3369            sin.sin_len = sizeof(sin);
     3370#endif
     3371            memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
     3372            tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
     3373
     3374            if (pch == h->h_addr_list && alen >= sizeof(sin))
     3375                memcpy((char *) addr, &sin, sizeof(sin));
     3376            break;
     3377            }
    32043378
    32053379#ifdef ENABLE_IPV6
    3206                 case AF_INET6:
    3207                     {
    3208                         struct sockaddr_in6 sin6;
    3209                         memset(&sin6, 0, sizeof(sin6));
    3210                         sin6.sin6_family = af;
     3380        case AF_INET6:
     3381            {
     3382            struct sockaddr_in6 sin6;
     3383            memset(&sin6, 0, sizeof(sin6));
     3384            sin6.sin6_family = af;
    32113385#ifdef HAVE_SOCKADDR_SA_LEN
    3212                         sin6.sin6_len = sizeof(sin6);
    3213 #endif
    3214                         memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
    3215                         tmp = makeipaddr((struct sockaddr *)&sin6,
    3216                                 sizeof(sin6));
    3217 
    3218                         if (pch == h->h_addr_list && alen >= sizeof(sin6))
    3219                                 memcpy((char *) addr, &sin6, sizeof(sin6));
    3220                         break;
    3221                     }
    3222 #endif
    3223 
    3224                 default:        /* can't happen */
    3225                         PyErr_SetString(socket_error,
    3226                                         "unsupported address family");
    3227                         return NULL;
    3228                 }
    3229 
    3230                 if (tmp == NULL)
    3231                         goto err;
    3232 
    3233                 status = PyList_Append(addr_list, tmp);
    3234                 Py_DECREF(tmp);
    3235 
    3236                 if (status)
    3237                         goto err;
    3238         }
    3239 
    3240         rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
     3386            sin6.sin6_len = sizeof(sin6);
     3387#endif
     3388            memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
     3389            tmp = makeipaddr((struct sockaddr *)&sin6,
     3390                sizeof(sin6));
     3391
     3392            if (pch == h->h_addr_list && alen >= sizeof(sin6))
     3393                memcpy((char *) addr, &sin6, sizeof(sin6));
     3394            break;
     3395            }
     3396#endif
     3397
     3398        default:                /* can't happen */
     3399            PyErr_SetString(socket_error,
     3400                            "unsupported address family");
     3401            return NULL;
     3402        }
     3403
     3404        if (tmp == NULL)
     3405            goto err;
     3406
     3407        status = PyList_Append(addr_list, tmp);
     3408        Py_DECREF(tmp);
     3409
     3410        if (status)
     3411            goto err;
     3412    }
     3413
     3414    rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
    32413415
    32423416 err:
    3243         Py_XDECREF(name_list);
    3244         Py_XDECREF(addr_list);
    3245         return rtn_tuple;
     3417    Py_XDECREF(name_list);
     3418    Py_XDECREF(addr_list);
     3419    return rtn_tuple;
    32463420}
    32473421
     
    32533427socket_gethostbyname_ex(PyObject *self, PyObject *args)
    32543428{
    3255         char *name;
    3256         struct hostent *h;
     3429    char *name;
     3430    struct hostent *h;
    32573431#ifdef ENABLE_IPV6
    3258         struct sockaddr_storage addr;
    3259 #else
    3260         struct sockaddr_in addr;
    3261 #endif
    3262         struct sockaddr *sa;
    3263         PyObject *ret;
     3432    struct sockaddr_storage addr;
     3433#else
     3434    struct sockaddr_in addr;
     3435#endif
     3436    struct sockaddr *sa;
     3437    PyObject *ret;
    32643438#ifdef HAVE_GETHOSTBYNAME_R
    3265         struct hostent hp_allocated;
     3439    struct hostent hp_allocated;
    32663440#ifdef HAVE_GETHOSTBYNAME_R_3_ARG
    3267         struct hostent_data data;
    3268 #else
    3269         char buf[16384];
    3270         int buf_len = (sizeof buf) - 1;
    3271         int errnop;
     3441    struct hostent_data data;
     3442#else
     3443    char buf[16384];
     3444    int buf_len = (sizeof buf) - 1;
     3445    int errnop;
    32723446#endif
    32733447#if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
    3274         int result;
     3448    int result;
    32753449#endif
    32763450#endif /* HAVE_GETHOSTBYNAME_R */
    32773451
    3278         if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
    3279                 return NULL;
    3280         if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
    3281                 return NULL;
    3282         Py_BEGIN_ALLOW_THREADS
     3452    if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
     3453        return NULL;
     3454    if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
     3455        return NULL;
     3456    Py_BEGIN_ALLOW_THREADS
    32833457#ifdef HAVE_GETHOSTBYNAME_R
    32843458#if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
    3285         result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
    3286                                 &h, &errnop);
     3459    result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
     3460                            &h, &errnop);
    32873461#elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
    3288         h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
     3462    h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
    32893463#else /* HAVE_GETHOSTBYNAME_R_3_ARG */
    3290         memset((void *) &data, '\0', sizeof(data));
    3291         result = gethostbyname_r(name, &hp_allocated, &data);
    3292         h = (result != 0) ? NULL : &hp_allocated;
     3464    memset((void *) &data, '\0', sizeof(data));
     3465    result = gethostbyname_r(name, &hp_allocated, &data);
     3466    h = (result != 0) ? NULL : &hp_allocated;
    32933467#endif
    32943468#else /* not HAVE_GETHOSTBYNAME_R */
    32953469#ifdef USE_GETHOSTBYNAME_LOCK
    3296         PyThread_acquire_lock(netdb_lock, 1);
    3297 #endif
    3298         h = gethostbyname(name);
     3470    PyThread_acquire_lock(netdb_lock, 1);
     3471#endif
     3472    h = gethostbyname(name);
    32993473#endif /* HAVE_GETHOSTBYNAME_R */
    3300         Py_END_ALLOW_THREADS
    3301         /* Some C libraries would require addr.__ss_family instead of
    3302            addr.ss_family.
    3303            Therefore, we cast the sockaddr_storage into sockaddr to
    3304            access sa_family. */
    3305         sa = (struct sockaddr*)&addr;
    3306         ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
    3307                              sa->sa_family);
     3474    Py_END_ALLOW_THREADS
     3475    /* Some C libraries would require addr.__ss_family instead of
     3476       addr.ss_family.
     3477       Therefore, we cast the sockaddr_storage into sockaddr to
     3478       access sa_family. */
     3479    sa = (struct sockaddr*)&addr;
     3480    ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
     3481                         sa->sa_family);
    33083482#ifdef USE_GETHOSTBYNAME_LOCK
    3309         PyThread_release_lock(netdb_lock);
    3310 #endif
    3311         return ret;
     3483    PyThread_release_lock(netdb_lock);
     3484#endif
     3485    return ret;
    33123486}
    33133487
     
    33263500{
    33273501#ifdef ENABLE_IPV6
    3328         struct sockaddr_storage addr;
    3329 #else
    3330         struct sockaddr_in addr;
    3331 #endif
    3332         struct sockaddr *sa = (struct sockaddr *)&addr;
    3333         char *ip_num;
    3334         struct hostent *h;
    3335         PyObject *ret;
     3502    struct sockaddr_storage addr;
     3503#else
     3504    struct sockaddr_in addr;
     3505#endif
     3506    struct sockaddr *sa = (struct sockaddr *)&addr;
     3507    char *ip_num;
     3508    struct hostent *h;
     3509    PyObject *ret;
    33363510#ifdef HAVE_GETHOSTBYNAME_R
    3337         struct hostent hp_allocated;
     3511    struct hostent hp_allocated;
    33383512#ifdef HAVE_GETHOSTBYNAME_R_3_ARG
    3339         struct hostent_data data;
    3340 #else
    3341         /* glibcs up to 2.10 assume that the buf argument to
    3342            gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
    3343            does not ensure. The attribute below instructs the compiler
    3344            to maintain this alignment. */
    3345         char buf[16384] Py_ALIGNED(8);
    3346         int buf_len = (sizeof buf) - 1;
    3347         int errnop;
     3513    struct hostent_data data;
     3514#else
     3515    /* glibcs up to 2.10 assume that the buf argument to
     3516       gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
     3517       does not ensure. The attribute below instructs the compiler
     3518       to maintain this alignment. */
     3519    char buf[16384] Py_ALIGNED(8);
     3520    int buf_len = (sizeof buf) - 1;
     3521    int errnop;
    33483522#endif
    33493523#if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
    3350         int result;
     3524    int result;
    33513525#endif
    33523526#endif /* HAVE_GETHOSTBYNAME_R */
    3353         char *ap;
    3354         int al;
    3355         int af;
    3356 
    3357         if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
    3358                 return NULL;
    3359         af = AF_UNSPEC;
    3360         if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
    3361                 return NULL;
    3362         af = sa->sa_family;
    3363         ap = NULL;
    3364         al = 0;
    3365         switch (af) {
    3366         case AF_INET:
    3367                 ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
    3368                 al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
    3369                 break;
     3527    char *ap;
     3528    int al;
     3529    int af;
     3530
     3531    if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
     3532        return NULL;
     3533    af = AF_UNSPEC;
     3534    if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
     3535        return NULL;
     3536    af = sa->sa_family;
     3537    ap = NULL;
     3538    switch (af) {
     3539    case AF_INET:
     3540        ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
     3541        al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
     3542        break;
    33703543#ifdef ENABLE_IPV6
    3371         case AF_INET6:
    3372                 ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
    3373                 al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
    3374                 break;
    3375 #endif
    3376         default:
    3377                 PyErr_SetString(socket_error, "unsupported address family");
    3378                 return NULL;
    3379         }
    3380         Py_BEGIN_ALLOW_THREADS
     3544    case AF_INET6:
     3545        ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
     3546        al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
     3547        break;
     3548#endif
     3549    default:
     3550        PyErr_SetString(socket_error, "unsupported address family");
     3551        return NULL;
     3552    }
     3553    Py_BEGIN_ALLOW_THREADS
    33813554#ifdef HAVE_GETHOSTBYNAME_R
    33823555#if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
    3383         result = gethostbyaddr_r(ap, al, af,
    3384                 &hp_allocated, buf, buf_len,
    3385                 &h, &errnop);
     3556    result = gethostbyaddr_r(ap, al, af,
     3557        &hp_allocated, buf, buf_len,
     3558        &h, &errnop);
    33863559#elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
    3387         h = gethostbyaddr_r(ap, al, af,
    3388                             &hp_allocated, buf, buf_len, &errnop);
     3560    h = gethostbyaddr_r(ap, al, af,
     3561                        &hp_allocated, buf, buf_len, &errnop);
    33893562#else /* HAVE_GETHOSTBYNAME_R_3_ARG */
    3390         memset((void *) &data, '\0', sizeof(data));
    3391         result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
    3392         h = (result != 0) ? NULL : &hp_allocated;
     3563    memset((void *) &data, '\0', sizeof(data));
     3564    result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
     3565    h = (result != 0) ? NULL : &hp_allocated;
    33933566#endif
    33943567#else /* not HAVE_GETHOSTBYNAME_R */
    33953568#ifdef USE_GETHOSTBYNAME_LOCK
    3396         PyThread_acquire_lock(netdb_lock, 1);
    3397 #endif
    3398         h = gethostbyaddr(ap, al, af);
     3569    PyThread_acquire_lock(netdb_lock, 1);
     3570#endif
     3571    h = gethostbyaddr(ap, al, af);
    33993572#endif /* HAVE_GETHOSTBYNAME_R */
    3400         Py_END_ALLOW_THREADS
    3401         ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
     3573    Py_END_ALLOW_THREADS
     3574    ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
    34023575#ifdef USE_GETHOSTBYNAME_LOCK
    3403         PyThread_release_lock(netdb_lock);
    3404 #endif
    3405         return ret;
     3576    PyThread_release_lock(netdb_lock);
     3577#endif
     3578    return ret;
    34063579}
    34073580
     
    34213594socket_getservbyname(PyObject *self, PyObject *args)
    34223595{
    3423         char *name, *proto=NULL;
    3424         struct servent *sp;
    3425         if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
    3426                 return NULL;
    3427         Py_BEGIN_ALLOW_THREADS
    3428         sp = getservbyname(name, proto);
    3429         Py_END_ALLOW_THREADS
    3430         if (sp == NULL) {
    3431                 PyErr_SetString(socket_error, "service/proto not found");
    3432                 return NULL;
    3433         }
    3434         return PyInt_FromLong((long) ntohs(sp->s_port));
     3596    char *name, *proto=NULL;
     3597    struct servent *sp;
     3598    if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
     3599        return NULL;
     3600    Py_BEGIN_ALLOW_THREADS
     3601    sp = getservbyname(name, proto);
     3602    Py_END_ALLOW_THREADS
     3603    if (sp == NULL) {
     3604        PyErr_SetString(socket_error, "service/proto not found");
     3605        return NULL;
     3606    }
     3607    return PyInt_FromLong((long) ntohs(sp->s_port));
    34353608}
    34363609
     
    34513624socket_getservbyport(PyObject *self, PyObject *args)
    34523625{
    3453         unsigned short port;
    3454         char *proto=NULL;
    3455         struct servent *sp;
    3456         if (!PyArg_ParseTuple(args, "H|s:getservbyport", &port, &proto))
    3457                 return NULL;
    3458         Py_BEGIN_ALLOW_THREADS
    3459         sp = getservbyport(htons(port), proto);
    3460         Py_END_ALLOW_THREADS
    3461         if (sp == NULL) {
    3462                 PyErr_SetString(socket_error, "port/proto not found");
    3463                 return NULL;
    3464         }
    3465         return PyString_FromString(sp->s_name);
     3626    int port;
     3627    char *proto=NULL;
     3628    struct servent *sp;
     3629    if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
     3630        return NULL;
     3631    if (port < 0 || port > 0xffff) {
     3632        PyErr_SetString(
     3633            PyExc_OverflowError,
     3634            "getservbyport: port must be 0-65535.");
     3635        return NULL;
     3636    }
     3637    Py_BEGIN_ALLOW_THREADS
     3638    sp = getservbyport(htons((short)port), proto);
     3639    Py_END_ALLOW_THREADS
     3640    if (sp == NULL) {
     3641        PyErr_SetString(socket_error, "port/proto not found");
     3642        return NULL;
     3643    }
     3644    return PyString_FromString(sp->s_name);
    34663645}
    34673646
     
    34813660socket_getprotobyname(PyObject *self, PyObject *args)
    34823661{
    3483         char *name;
    3484         struct protoent *sp;
     3662    char *name;
     3663    struct protoent *sp;
    34853664#ifdef __BEOS__
    34863665/* Not available in BeOS yet. - [cjh] */
    3487         PyErr_SetString(socket_error, "getprotobyname not supported");
    3488         return NULL;
    3489 #else
    3490         if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
    3491                 return NULL;
    3492         Py_BEGIN_ALLOW_THREADS
    3493         sp = getprotobyname(name);
    3494         Py_END_ALLOW_THREADS
    3495         if (sp == NULL) {
    3496                 PyErr_SetString(socket_error, "protocol not found");
    3497                 return NULL;
    3498         }
    3499         return PyInt_FromLong((long) sp->p_proto);
     3666    PyErr_SetString(socket_error, "getprotobyname not supported");
     3667    return NULL;
     3668#else
     3669    if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
     3670        return NULL;
     3671    Py_BEGIN_ALLOW_THREADS
     3672    sp = getprotobyname(name);
     3673    Py_END_ALLOW_THREADS
     3674    if (sp == NULL) {
     3675        PyErr_SetString(socket_error, "protocol not found");
     3676        return NULL;
     3677    }
     3678    return PyInt_FromLong((long) sp->p_proto);
    35003679#endif
    35013680}
     
    35163695socket_socketpair(PyObject *self, PyObject *args)
    35173696{
    3518         PySocketSockObject *s0 = NULL, *s1 = NULL;
    3519         SOCKET_T sv[2];
    3520         int family, type = SOCK_STREAM, proto = 0;
    3521         PyObject *res = NULL;
     3697    PySocketSockObject *s0 = NULL, *s1 = NULL;
     3698    SOCKET_T sv[2];
     3699    int family, type = SOCK_STREAM, proto = 0;
     3700    PyObject *res = NULL;
    35223701
    35233702#if defined(AF_UNIX)
    3524         family = AF_UNIX;
    3525 #else
    3526         family = AF_INET;
    3527 #endif
    3528         if (!PyArg_ParseTuple(args, "|iii:socketpair",
    3529                               &family, &type, &proto))
    3530                 return NULL;
    3531         /* Create a pair of socket fds */
    3532         if (socketpair(family, type, proto, sv) < 0)
    3533                 return set_error();
    3534         s0 = new_sockobject(sv[0], family, type, proto);
    3535         if (s0 == NULL)
    3536                 goto finally;
    3537         s1 = new_sockobject(sv[1], family, type, proto);
    3538         if (s1 == NULL)
    3539                 goto finally;
    3540         res = PyTuple_Pack(2, s0, s1);
     3703    family = AF_UNIX;
     3704#else
     3705    family = AF_INET;
     3706#endif
     3707    if (!PyArg_ParseTuple(args, "|iii:socketpair",
     3708                          &family, &type, &proto))
     3709        return NULL;
     3710    /* Create a pair of socket fds */
     3711    if (socketpair(family, type, proto, sv) < 0)
     3712        return set_error();
     3713    s0 = new_sockobject(sv[0], family, type, proto);
     3714    if (s0 == NULL)
     3715        goto finally;
     3716    s1 = new_sockobject(sv[1], family, type, proto);
     3717    if (s1 == NULL)
     3718        goto finally;
     3719    res = PyTuple_Pack(2, s0, s1);
    35413720
    35423721finally:
    3543         if (res == NULL) {
    3544                 if (s0 == NULL)
    3545                         SOCKETCLOSE(sv[0]);
    3546                 if (s1 == NULL)
    3547                         SOCKETCLOSE(sv[1]);
    3548         }
    3549         Py_XDECREF(s0);
    3550         Py_XDECREF(s1);
    3551         return res;
     3722    if (res == NULL) {
     3723        if (s0 == NULL)
     3724            SOCKETCLOSE(sv[0]);
     3725        if (s1 == NULL)
     3726            SOCKETCLOSE(sv[1]);
     3727    }
     3728    Py_XDECREF(s0);
     3729    Py_XDECREF(s1);
     3730    return res;
    35523731}
    35533732
     
    35723751socket_fromfd(PyObject *self, PyObject *args)
    35733752{
    3574         PySocketSockObject *s;
    3575         SOCKET_T fd;
    3576         int family, type, proto = 0;
    3577         if (!PyArg_ParseTuple(args, "iii|i:fromfd",
    3578                               &fd, &family, &type, &proto))
    3579                 return NULL;
    3580         /* Dup the fd so it and the socket can be closed independently */
    3581         fd = dup(fd);
    3582         if (fd < 0)
    3583                 return set_error();
    3584         s = new_sockobject(fd, family, type, proto);
    3585         return (PyObject *) s;
     3753    PySocketSockObject *s;
     3754    SOCKET_T fd;
     3755    int family, type, proto = 0;
     3756    if (!PyArg_ParseTuple(args, "iii|i:fromfd",
     3757                          &fd, &family, &type, &proto))
     3758        return NULL;
     3759    /* Dup the fd so it and the socket can be closed independently */
     3760    fd = dup(fd);
     3761    if (fd < 0)
     3762        return set_error();
     3763    s = new_sockobject(fd, family, type, proto);
     3764    return (PyObject *) s;
    35863765}
    35873766
     
    35993778socket_ntohs(PyObject *self, PyObject *args)
    36003779{
    3601         int x1, x2;
    3602 
    3603         if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
    3604                 return NULL;
    3605         }
    3606         if (x1 < 0) {
    3607                 PyErr_SetString(PyExc_OverflowError,
    3608                         "can't convert negative number to unsigned long");
    3609                 return NULL;
    3610         }
    3611         x2 = (unsigned int)ntohs((unsigned short)x1);
    3612         return PyInt_FromLong(x2);
     3780    int x1, x2;
     3781
     3782    if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
     3783        return NULL;
     3784    }
     3785    if (x1 < 0) {
     3786        PyErr_SetString(PyExc_OverflowError,
     3787            "can't convert negative number to unsigned long");
     3788        return NULL;
     3789    }
     3790    x2 = (unsigned int)ntohs((unsigned short)x1);
     3791    return PyInt_FromLong(x2);
    36133792}
    36143793
     
    36223801socket_ntohl(PyObject *self, PyObject *arg)
    36233802{
    3624         unsigned long x;
    3625 
    3626         if (PyInt_Check(arg)) {
    3627                 x = PyInt_AS_LONG(arg);
    3628                 if (x == (unsigned long) -1 && PyErr_Occurred())
    3629                         return NULL;
    3630                 if ((long)x < 0) {
    3631                         PyErr_SetString(PyExc_OverflowError,
    3632                           "can't convert negative number to unsigned long");
    3633                         return NULL;
    3634                 }
    3635         }
    3636         else if (PyLong_Check(arg)) {
    3637                 x = PyLong_AsUnsignedLong(arg);
    3638                 if (x == (unsigned long) -1 && PyErr_Occurred())
    3639                         return NULL;
     3803    unsigned long x;
     3804
     3805    if (PyInt_Check(arg)) {
     3806        x = PyInt_AS_LONG(arg);
     3807        if (x == (unsigned long) -1 && PyErr_Occurred())
     3808            return NULL;
     3809        if ((long)x < 0) {
     3810            PyErr_SetString(PyExc_OverflowError,
     3811              "can't convert negative number to unsigned long");
     3812            return NULL;
     3813        }
     3814    }
     3815    else if (PyLong_Check(arg)) {
     3816        x = PyLong_AsUnsignedLong(arg);
     3817        if (x == (unsigned long) -1 && PyErr_Occurred())
     3818            return NULL;
    36403819#if SIZEOF_LONG > 4
    3641                 {
    3642                         unsigned long y;
    3643                         /* only want the trailing 32 bits */
    3644                         y = x & 0xFFFFFFFFUL;
    3645                         if (y ^ x)
    3646                                 return PyErr_Format(PyExc_OverflowError,
    3647                                             "long int larger than 32 bits");
    3648                         x = y;
    3649                 }
    3650 #endif
    3651         }
    3652         else
    3653                 return PyErr_Format(PyExc_TypeError,
    3654                                     "expected int/long, %s found",
    3655                                     Py_TYPE(arg)->tp_name);
    3656         if (x == (unsigned long) -1 && PyErr_Occurred())
    3657                 return NULL;
    3658         return PyLong_FromUnsignedLong(ntohl(x));
     3820        {
     3821            unsigned long y;
     3822            /* only want the trailing 32 bits */
     3823            y = x & 0xFFFFFFFFUL;
     3824            if (y ^ x)
     3825                return PyErr_Format(PyExc_OverflowError,
     3826                            "long int larger than 32 bits");
     3827            x = y;
     3828        }
     3829#endif
     3830    }
     3831    else
     3832        return PyErr_Format(PyExc_TypeError,
     3833                            "expected int/long, %s found",
     3834                            Py_TYPE(arg)->tp_name);
     3835    if (x == (unsigned long) -1 && PyErr_Occurred())
     3836        return NULL;
     3837    return PyLong_FromUnsignedLong(ntohl(x));
    36593838}
    36603839
     
    36683847socket_htons(PyObject *self, PyObject *args)
    36693848{
    3670         int x1, x2;
    3671 
    3672         if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
    3673                 return NULL;
    3674         }
    3675         if (x1 < 0) {
    3676                 PyErr_SetString(PyExc_OverflowError,
    3677                         "can't convert negative number to unsigned long");
    3678                 return NULL;
    3679         }
    3680         x2 = (unsigned int)htons((unsigned short)x1);
    3681         return PyInt_FromLong(x2);
     3849    int x1, x2;
     3850
     3851    if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
     3852        return NULL;
     3853    }
     3854    if (x1 < 0) {
     3855        PyErr_SetString(PyExc_OverflowError,
     3856            "can't convert negative number to unsigned long");
     3857        return NULL;
     3858    }
     3859    x2 = (unsigned int)htons((unsigned short)x1);
     3860    return PyInt_FromLong(x2);
    36823861}
    36833862
     
    36913870socket_htonl(PyObject *self, PyObject *arg)
    36923871{
    3693         unsigned long x;
    3694 
    3695         if (PyInt_Check(arg)) {
    3696                 x = PyInt_AS_LONG(arg);
    3697                 if (x == (unsigned long) -1 && PyErr_Occurred())
    3698                         return NULL;
    3699                 if ((long)x < 0) {
    3700                         PyErr_SetString(PyExc_OverflowError,
    3701                           "can't convert negative number to unsigned long");
    3702                         return NULL;
    3703                 }
    3704         }
    3705         else if (PyLong_Check(arg)) {
    3706                 x = PyLong_AsUnsignedLong(arg);
    3707                 if (x == (unsigned long) -1 && PyErr_Occurred())
    3708                         return NULL;
     3872    unsigned long x;
     3873
     3874    if (PyInt_Check(arg)) {
     3875        x = PyInt_AS_LONG(arg);
     3876        if (x == (unsigned long) -1 && PyErr_Occurred())
     3877            return NULL;
     3878        if ((long)x < 0) {
     3879            PyErr_SetString(PyExc_OverflowError,
     3880              "can't convert negative number to unsigned long");
     3881            return NULL;
     3882        }
     3883    }
     3884    else if (PyLong_Check(arg)) {
     3885        x = PyLong_AsUnsignedLong(arg);
     3886        if (x == (unsigned long) -1 && PyErr_Occurred())
     3887            return NULL;
    37093888#if SIZEOF_LONG > 4
    3710                 {
    3711                         unsigned long y;
    3712                         /* only want the trailing 32 bits */
    3713                         y = x & 0xFFFFFFFFUL;
    3714                         if (y ^ x)
    3715                                 return PyErr_Format(PyExc_OverflowError,
    3716                                             "long int larger than 32 bits");
    3717                         x = y;
    3718                 }
    3719 #endif
    3720         }
    3721         else
    3722                 return PyErr_Format(PyExc_TypeError,
    3723                                     "expected int/long, %s found",
    3724                                     Py_TYPE(arg)->tp_name);
    3725         return PyLong_FromUnsignedLong(htonl((unsigned long)x));
     3889        {
     3890            unsigned long y;
     3891            /* only want the trailing 32 bits */
     3892            y = x & 0xFFFFFFFFUL;
     3893            if (y ^ x)
     3894                return PyErr_Format(PyExc_OverflowError,
     3895                            "long int larger than 32 bits");
     3896            x = y;
     3897        }
     3898#endif
     3899    }
     3900    else
     3901        return PyErr_Format(PyExc_TypeError,
     3902                            "expected int/long, %s found",
     3903                            Py_TYPE(arg)->tp_name);
     3904    return PyLong_FromUnsignedLong(htonl((unsigned long)x));
    37263905}
    37273906
     
    37463925#endif
    37473926#ifdef HAVE_INET_ATON
    3748         struct in_addr buf;
     3927    struct in_addr buf;
    37493928#endif
    37503929
     
    37533932#error "Not sure if in_addr_t exists and int is not 32-bits."
    37543933#endif
    3755         /* Have to use inet_addr() instead */
    3756         unsigned int packed_addr;
    3757 #endif
    3758         char *ip_addr;
    3759 
    3760         if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
    3761                 return NULL;
     3934    /* Have to use inet_addr() instead */
     3935    unsigned int packed_addr;
     3936#endif
     3937    char *ip_addr;
     3938
     3939    if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
     3940        return NULL;
    37623941
    37633942
     
    37673946    if (inet_aton != NULL) {
    37683947#endif
    3769         if (inet_aton(ip_addr, &buf))
    3770                 return PyString_FromStringAndSize((char *)(&buf),
    3771                                                   sizeof(buf));
    3772 
    3773         PyErr_SetString(socket_error,
    3774                         "illegal IP address string passed to inet_aton");
    3775         return NULL;
     3948    if (inet_aton(ip_addr, &buf))
     3949        return PyString_FromStringAndSize((char *)(&buf),
     3950                                          sizeof(buf));
     3951
     3952    PyErr_SetString(socket_error,
     3953                    "illegal IP address string passed to inet_aton");
     3954    return NULL;
    37763955
    37773956#ifdef USE_INET_ATON_WEAKLINK
     
    37833962#if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
    37843963
    3785         /* special-case this address as inet_addr might return INADDR_NONE
    3786         * for this */
    3787         if (strcmp(ip_addr, "255.255.255.255") == 0) {
    3788                 packed_addr = 0xFFFFFFFF;
    3789         } else {
    3790 
    3791                 packed_addr = inet_addr(ip_addr);
    3792 
    3793                 if (packed_addr == INADDR_NONE) {       /* invalid address */
    3794                         PyErr_SetString(socket_error,
    3795                                 "illegal IP address string passed to inet_aton");
    3796                         return NULL;
    3797                 }
    3798         }
    3799         return PyString_FromStringAndSize((char *) &packed_addr,
    3800                                           sizeof(packed_addr));
     3964    /* special-case this address as inet_addr might return INADDR_NONE
     3965    * for this */
     3966    if (strcmp(ip_addr, "255.255.255.255") == 0) {
     3967        packed_addr = 0xFFFFFFFF;
     3968    } else {
     3969
     3970        packed_addr = inet_addr(ip_addr);
     3971
     3972        if (packed_addr == INADDR_NONE) {               /* invalid address */
     3973            PyErr_SetString(socket_error,
     3974                "illegal IP address string passed to inet_aton");
     3975            return NULL;
     3976        }
     3977    }
     3978    return PyString_FromStringAndSize((char *) &packed_addr,
     3979                                      sizeof(packed_addr));
    38013980
    38023981#ifdef USE_INET_ATON_WEAKLINK
     
    38153994socket_inet_ntoa(PyObject *self, PyObject *args)
    38163995{
    3817         char *packed_str;
    3818         int addr_len;
    3819         struct in_addr packed_addr;
    3820 
    3821         if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
    3822                 return NULL;
    3823         }
    3824 
    3825         if (addr_len != sizeof(packed_addr)) {
    3826                 PyErr_SetString(socket_error,
    3827                         "packed IP wrong length for inet_ntoa");
    3828                 return NULL;
    3829         }
    3830 
    3831         memcpy(&packed_addr, packed_str, addr_len);
    3832 
    3833         return PyString_FromString(inet_ntoa(packed_addr));
     3996    char *packed_str;
     3997    int addr_len;
     3998    struct in_addr packed_addr;
     3999
     4000    if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
     4001        return NULL;
     4002    }
     4003
     4004    if (addr_len != sizeof(packed_addr)) {
     4005        PyErr_SetString(socket_error,
     4006            "packed IP wrong length for inet_ntoa");
     4007        return NULL;
     4008    }
     4009
     4010    memcpy(&packed_addr, packed_str, addr_len);
     4011
     4012    return PyString_FromString(inet_ntoa(packed_addr));
    38344013}
    38354014
     
    38454024socket_inet_pton(PyObject *self, PyObject *args)
    38464025{
    3847         int af;
    3848         char* ip;
    3849         int retval;
     4026    int af;
     4027    char* ip;
     4028    int retval;
    38504029#ifdef ENABLE_IPV6
    3851         char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
    3852 #else
    3853         char packed[sizeof(struct in_addr)];
    3854 #endif
    3855         if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
    3856                 return NULL;
    3857         }
     4030    char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
     4031#else
     4032    char packed[sizeof(struct in_addr)];
     4033#endif
     4034    if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
     4035        return NULL;
     4036    }
    38584037
    38594038#if !defined(ENABLE_IPV6) && defined(AF_INET6)
    3860         if(af == AF_INET6) {
    3861                 PyErr_SetString(socket_error,
    3862                                 "can't use AF_INET6, IPv6 is disabled");
    3863                 return NULL;
    3864         }
    3865 #endif
    3866 
    3867         retval = inet_pton(af, ip, packed);
    3868         if (retval < 0) {
    3869                 PyErr_SetFromErrno(socket_error);
    3870                 return NULL;
    3871         } else if (retval == 0) {
    3872                 PyErr_SetString(socket_error,
    3873                         "illegal IP address string passed to inet_pton");
    3874                 return NULL;
    3875         } else if (af == AF_INET) {
    3876                 return PyString_FromStringAndSize(packed,
    3877                         sizeof(struct in_addr));
     4039    if(af == AF_INET6) {
     4040        PyErr_SetString(socket_error,
     4041                        "can't use AF_INET6, IPv6 is disabled");
     4042        return NULL;
     4043    }
     4044#endif
     4045
     4046    retval = inet_pton(af, ip, packed);
     4047    if (retval < 0) {
     4048        PyErr_SetFromErrno(socket_error);
     4049        return NULL;
     4050    } else if (retval == 0) {
     4051        PyErr_SetString(socket_error,
     4052            "illegal IP address string passed to inet_pton");
     4053        return NULL;
     4054    } else if (af == AF_INET) {
     4055        return PyString_FromStringAndSize(packed,
     4056            sizeof(struct in_addr));
    38784057#ifdef ENABLE_IPV6
    3879         } else if (af == AF_INET6) {
    3880                 return PyString_FromStringAndSize(packed,
    3881                         sizeof(struct in6_addr));
    3882 #endif
    3883         } else {
    3884                 PyErr_SetString(socket_error, "unknown address family");
    3885                 return NULL;
    3886         }
     4058    } else if (af == AF_INET6) {
     4059        return PyString_FromStringAndSize(packed,
     4060            sizeof(struct in6_addr));
     4061#endif
     4062    } else {
     4063        PyErr_SetString(socket_error, "unknown address family");
     4064        return NULL;
     4065    }
    38874066}
    38884067
     
    38954074socket_inet_ntop(PyObject *self, PyObject *args)
    38964075{
    3897         int af;
    3898         char* packed;
    3899         int len;
    3900         const char* retval;
     4076    int af;
     4077    char* packed;
     4078    int len;
     4079    const char* retval;
    39014080#ifdef ENABLE_IPV6
    3902         char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
    3903 #else
    3904         char ip[INET_ADDRSTRLEN + 1];
    3905 #endif
    3906 
    3907         /* Guarantee NUL-termination for PyString_FromString() below */
    3908         memset((void *) &ip[0], '\0', sizeof(ip));
    3909 
    3910         if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
    3911                 return NULL;
    3912         }
    3913 
    3914         if (af == AF_INET) {
    3915                 if (len != sizeof(struct in_addr)) {
    3916                         PyErr_SetString(PyExc_ValueError,
    3917                                 "invalid length of packed IP address string");
    3918                         return NULL;
    3919                 }
     4081    char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
     4082#else
     4083    char ip[INET_ADDRSTRLEN + 1];
     4084#endif
     4085
     4086    /* Guarantee NUL-termination for PyString_FromString() below */
     4087    memset((void *) &ip[0], '\0', sizeof(ip));
     4088
     4089    if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
     4090        return NULL;
     4091    }
     4092
     4093    if (af == AF_INET) {
     4094        if (len != sizeof(struct in_addr)) {
     4095            PyErr_SetString(PyExc_ValueError,
     4096                "invalid length of packed IP address string");
     4097            return NULL;
     4098        }
    39204099#ifdef ENABLE_IPV6
    3921         } else if (af == AF_INET6) {
    3922                 if (len != sizeof(struct in6_addr)) {
    3923                         PyErr_SetString(PyExc_ValueError,
    3924                                 "invalid length of packed IP address string");
    3925                         return NULL;
    3926                 }
    3927 #endif
    3928         } else {
    3929                 PyErr_Format(PyExc_ValueError,
    3930                         "unknown address family %d", af);
    3931                 return NULL;
    3932         }
    3933 
    3934         retval = inet_ntop(af, packed, ip, sizeof(ip));
    3935         if (!retval) {
    3936                 PyErr_SetFromErrno(socket_error);
    3937                 return NULL;
    3938         } else {
    3939                 return PyString_FromString(retval);
    3940         }
    3941 
    3942         /* NOTREACHED */
    3943         PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
    3944         return NULL;
     4100    } else if (af == AF_INET6) {
     4101        if (len != sizeof(struct in6_addr)) {
     4102            PyErr_SetString(PyExc_ValueError,
     4103                "invalid length of packed IP address string");
     4104            return NULL;
     4105        }
     4106#endif
     4107    } else {
     4108        PyErr_Format(PyExc_ValueError,
     4109            "unknown address family %d", af);
     4110        return NULL;
     4111    }
     4112
     4113    retval = inet_ntop(af, packed, ip, sizeof(ip));
     4114    if (!retval) {
     4115        PyErr_SetFromErrno(socket_error);
     4116        return NULL;
     4117    } else {
     4118        return PyString_FromString(retval);
     4119    }
     4120
     4121    /* NOTREACHED */
     4122    PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
     4123    return NULL;
    39454124}
    39464125
     
    39534132socket_getaddrinfo(PyObject *self, PyObject *args)
    39544133{
    3955         struct addrinfo hints, *res;
    3956         struct addrinfo *res0 = NULL;
    3957         PyObject *hobj = NULL;
    3958         PyObject *pobj = (PyObject *)NULL;
    3959         char pbuf[30];
    3960         char *hptr, *pptr;
    3961         int family, socktype, protocol, flags;
    3962         int error;
    3963         PyObject *all = (PyObject *)NULL;
    3964         PyObject *single = (PyObject *)NULL;
    3965         PyObject *idna = NULL;
    3966 
    3967         family = socktype = protocol = flags = 0;
    3968         family = AF_UNSPEC;
    3969         if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
    3970                               &hobj, &pobj, &family, &socktype,
    3971                               &protocol, &flags)) {
    3972                 return NULL;
    3973         }
    3974         if (hobj == Py_None) {
    3975                 hptr = NULL;
    3976         } else if (PyUnicode_Check(hobj)) {
    3977                 idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
    3978                 if (!idna)
    3979                         return NULL;
    3980                 hptr = PyString_AsString(idna);
    3981         } else if (PyString_Check(hobj)) {
    3982                 hptr = PyString_AsString(hobj);
    3983         } else {
    3984                 PyErr_SetString(PyExc_TypeError,
    3985                                 "getaddrinfo() argument 1 must be string or None");
    3986                 return NULL;
    3987         }
    3988         if (PyInt_Check(pobj)) {
    3989                 PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
    3990                 pptr = pbuf;
    3991         } else if (PyString_Check(pobj)) {
    3992                 pptr = PyString_AsString(pobj);
    3993         } else if (pobj == Py_None) {
    3994                 pptr = (char *)NULL;
    3995         } else {
    3996                 PyErr_SetString(socket_error, "Int or String expected");
    3997                 goto err;
    3998         }
    3999         memset(&hints, 0, sizeof(hints));
    4000         hints.ai_family = family;
    4001         hints.ai_socktype = socktype;
    4002         hints.ai_protocol = protocol;
    4003         hints.ai_flags = flags;
    4004         Py_BEGIN_ALLOW_THREADS
    4005         ACQUIRE_GETADDRINFO_LOCK
    4006         error = getaddrinfo(hptr, pptr, &hints, &res0);
    4007         Py_END_ALLOW_THREADS
    4008         RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
    4009         if (error) {
    4010                 set_gaierror(error);
    4011                 goto err;
    4012         }
    4013 
    4014         if ((all = PyList_New(0)) == NULL)
    4015                 goto err;
    4016         for (res = res0; res; res = res->ai_next) {
    4017                 PyObject *addr =
    4018                         makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
    4019                 if (addr == NULL)
    4020                         goto err;
    4021                 single = Py_BuildValue("iiisO", res->ai_family,
    4022                         res->ai_socktype, res->ai_protocol,
    4023                         res->ai_canonname ? res->ai_canonname : "",
    4024                         addr);
    4025                 Py_DECREF(addr);
    4026                 if (single == NULL)
    4027                         goto err;
    4028 
    4029                 if (PyList_Append(all, single))
    4030                         goto err;
    4031                 Py_XDECREF(single);
    4032         }
    4033         Py_XDECREF(idna);
    4034         if (res0)
    4035                 freeaddrinfo(res0);
    4036         return all;
     4134    struct addrinfo hints, *res;
     4135    struct addrinfo *res0 = NULL;
     4136    PyObject *hobj = NULL;
     4137    PyObject *pobj = (PyObject *)NULL;
     4138    char pbuf[30];
     4139    char *hptr, *pptr;
     4140    int family, socktype, protocol, flags;
     4141    int error;
     4142    PyObject *all = (PyObject *)NULL;
     4143    PyObject *single = (PyObject *)NULL;
     4144    PyObject *idna = NULL;
     4145
     4146    family = socktype = protocol = flags = 0;
     4147    family = AF_UNSPEC;
     4148    if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
     4149                          &hobj, &pobj, &family, &socktype,
     4150                          &protocol, &flags)) {
     4151        return NULL;
     4152    }
     4153    if (hobj == Py_None) {
     4154        hptr = NULL;
     4155    } else if (PyUnicode_Check(hobj)) {
     4156        idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
     4157        if (!idna)
     4158            return NULL;
     4159        hptr = PyString_AsString(idna);
     4160    } else if (PyString_Check(hobj)) {
     4161        hptr = PyString_AsString(hobj);
     4162    } else {
     4163        PyErr_SetString(PyExc_TypeError,
     4164                        "getaddrinfo() argument 1 must be string or None");
     4165        return NULL;
     4166    }
     4167    if (PyInt_Check(pobj) || PyLong_Check(pobj)) {
     4168        long value = PyLong_AsLong(pobj);
     4169        if (value == -1 && PyErr_Occurred())
     4170            return NULL;
     4171        PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", value);
     4172        pptr = pbuf;
     4173    } else if (PyString_Check(pobj)) {
     4174        pptr = PyString_AsString(pobj);
     4175    } else if (pobj == Py_None) {
     4176        pptr = (char *)NULL;
     4177    } else {
     4178        PyErr_SetString(socket_error,
     4179                        "getaddrinfo() argument 2 must be integer or string");
     4180        goto err;
     4181    }
     4182#if defined(__APPLE__) && defined(AI_NUMERICSERV)
     4183    if ((flags & AI_NUMERICSERV) && (pptr == NULL || (pptr[0] == '0' && pptr[1] == 0))) {
     4184        /* On OSX upto at least OSX 10.8 getaddrinfo crashes
     4185         * if AI_NUMERICSERV is set and the servname is NULL or "0".
     4186         * This workaround avoids a segfault in libsystem.
     4187         */
     4188        pptr = "00";
     4189    }
     4190#endif
     4191    memset(&hints, 0, sizeof(hints));
     4192    hints.ai_family = family;
     4193    hints.ai_socktype = socktype;
     4194    hints.ai_protocol = protocol;
     4195    hints.ai_flags = flags;
     4196    Py_BEGIN_ALLOW_THREADS
     4197    ACQUIRE_GETADDRINFO_LOCK
     4198    error = getaddrinfo(hptr, pptr, &hints, &res0);
     4199    Py_END_ALLOW_THREADS
     4200    RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
     4201    if (error) {
     4202        set_gaierror(error);
     4203        goto err;
     4204    }
     4205
     4206    if ((all = PyList_New(0)) == NULL)
     4207        goto err;
     4208    for (res = res0; res; res = res->ai_next) {
     4209        PyObject *addr =
     4210            makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
     4211        if (addr == NULL)
     4212            goto err;
     4213        single = Py_BuildValue("iiisO", res->ai_family,
     4214            res->ai_socktype, res->ai_protocol,
     4215            res->ai_canonname ? res->ai_canonname : "",
     4216            addr);
     4217        Py_DECREF(addr);
     4218        if (single == NULL)
     4219            goto err;
     4220
     4221        if (PyList_Append(all, single))
     4222            goto err;
     4223        Py_XDECREF(single);
     4224    }
     4225    Py_XDECREF(idna);
     4226    if (res0)
     4227        freeaddrinfo(res0);
     4228    return all;
    40374229 err:
    4038         Py_XDECREF(single);
    4039         Py_XDECREF(all);
    4040         Py_XDECREF(idna);
    4041         if (res0)
    4042                 freeaddrinfo(res0);
    4043         return (PyObject *)NULL;
     4230    Py_XDECREF(single);
     4231    Py_XDECREF(all);
     4232    Py_XDECREF(idna);
     4233    if (res0)
     4234        freeaddrinfo(res0);
     4235    return (PyObject *)NULL;
    40444236}
    40454237
     
    40564248socket_getnameinfo(PyObject *self, PyObject *args)
    40574249{
    4058         PyObject *sa = (PyObject *)NULL;
    4059         int flags;
    4060         char *hostp;
    4061         int port, flowinfo, scope_id;
    4062         char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
    4063         struct addrinfo hints, *res = NULL;
    4064         int error;
    4065         PyObject *ret = (PyObject *)NULL;
    4066 
    4067         flags = flowinfo = scope_id = 0;
    4068         if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
    4069                 return NULL;
    4070         if (!PyTuple_Check(sa)) {
    4071                 PyErr_SetString(PyExc_TypeError,
    4072                                 "getnameinfo() argument 1 must be a tuple");
    4073                 return NULL;
    4074         }
    4075         if (!PyArg_ParseTuple(sa, "si|ii",
    4076                               &hostp, &port, &flowinfo, &scope_id))
    4077                 return NULL;
    4078         PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
    4079         memset(&hints, 0, sizeof(hints));
    4080         hints.ai_family = AF_UNSPEC;
    4081         hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
    4082         Py_BEGIN_ALLOW_THREADS
    4083         ACQUIRE_GETADDRINFO_LOCK
    4084         error = getaddrinfo(hostp, pbuf, &hints, &res);
    4085         Py_END_ALLOW_THREADS
    4086         RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
    4087         if (error) {
    4088                 set_gaierror(error);
    4089                 goto fail;
    4090         }
    4091         if (res->ai_next) {
    4092                 PyErr_SetString(socket_error,
    4093                         "sockaddr resolved to multiple addresses");
    4094                 goto fail;
    4095         }
    4096         switch (res->ai_family) {
    4097         case AF_INET:
    4098             {
    4099                 if (PyTuple_GET_SIZE(sa) != 2) {
    4100                         PyErr_SetString(socket_error,
    4101                                 "IPv4 sockaddr must be 2 tuple");
    4102                         goto fail;
    4103                 }
    4104                 break;
    4105             }
     4250    PyObject *sa = (PyObject *)NULL;
     4251    int flags;
     4252    char *hostp;
     4253    int port;
     4254    unsigned int flowinfo, scope_id;
     4255    char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
     4256    struct addrinfo hints, *res = NULL;
     4257    int error;
     4258    PyObject *ret = (PyObject *)NULL;
     4259
     4260    flags = flowinfo = scope_id = 0;
     4261    if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
     4262        return NULL;
     4263    if (!PyTuple_Check(sa)) {
     4264        PyErr_SetString(PyExc_TypeError,
     4265                        "getnameinfo() argument 1 must be a tuple");
     4266        return NULL;
     4267    }
     4268    if (!PyArg_ParseTuple(sa, "si|II",
     4269                          &hostp, &port, &flowinfo, &scope_id))
     4270        return NULL;
     4271    if (flowinfo > 0xfffff) {
     4272        PyErr_SetString(PyExc_OverflowError,
     4273                        "getsockaddrarg: flowinfo must be 0-1048575.");
     4274        return NULL;
     4275    }
     4276    PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
     4277    memset(&hints, 0, sizeof(hints));
     4278    hints.ai_family = AF_UNSPEC;
     4279    hints.ai_socktype = SOCK_DGRAM;     /* make numeric port happy */
     4280    Py_BEGIN_ALLOW_THREADS
     4281    ACQUIRE_GETADDRINFO_LOCK
     4282    error = getaddrinfo(hostp, pbuf, &hints, &res);
     4283    Py_END_ALLOW_THREADS
     4284    RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
     4285    if (error) {
     4286        set_gaierror(error);
     4287        goto fail;
     4288    }
     4289    if (res->ai_next) {
     4290        PyErr_SetString(socket_error,
     4291            "sockaddr resolved to multiple addresses");
     4292        goto fail;
     4293    }
     4294    switch (res->ai_family) {
     4295    case AF_INET:
     4296        {
     4297        if (PyTuple_GET_SIZE(sa) != 2) {
     4298            PyErr_SetString(socket_error,
     4299                "IPv4 sockaddr must be 2 tuple");
     4300            goto fail;
     4301        }
     4302        break;
     4303        }
    41064304#ifdef ENABLE_IPV6
    4107         case AF_INET6:
    4108             {
    4109                 struct sockaddr_in6 *sin6;
    4110                 sin6 = (struct sockaddr_in6 *)res->ai_addr;
    4111                 sin6->sin6_flowinfo = flowinfo;
    4112                 sin6->sin6_scope_id = scope_id;
    4113                 break;
    4114             }
    4115 #endif
    4116         }
    4117         error = getnameinfo(res->ai_addr, res->ai_addrlen,
    4118                         hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
    4119         if (error) {
    4120                 set_gaierror(error);
    4121                 goto fail;
    4122         }
    4123         ret = Py_BuildValue("ss", hbuf, pbuf);
     4305    case AF_INET6:
     4306        {
     4307        struct sockaddr_in6 *sin6;
     4308        sin6 = (struct sockaddr_in6 *)res->ai_addr;
     4309        sin6->sin6_flowinfo = htonl(flowinfo);
     4310        sin6->sin6_scope_id = scope_id;
     4311        break;
     4312        }
     4313#endif
     4314    }
     4315    error = getnameinfo(res->ai_addr, res->ai_addrlen,
     4316                    hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
     4317    if (error) {
     4318        set_gaierror(error);
     4319        goto fail;
     4320    }
     4321    ret = Py_BuildValue("ss", hbuf, pbuf);
    41244322
    41254323fail:
    4126         if (res)
    4127                 freeaddrinfo(res);
    4128         return ret;
     4324    if (res)
     4325        freeaddrinfo(res);
     4326    return ret;
    41294327}
    41304328
     
    41404338socket_getdefaulttimeout(PyObject *self)
    41414339{
    4142         if (defaulttimeout < 0.0) {
    4143                 Py_INCREF(Py_None);
    4144                 return Py_None;
    4145         }
    4146         else
    4147                 return PyFloat_FromDouble(defaulttimeout);
     4340    if (defaulttimeout < 0.0) {
     4341        Py_INCREF(Py_None);
     4342        return Py_None;
     4343    }
     4344    else
     4345        return PyFloat_FromDouble(defaulttimeout);
    41484346}
    41494347
     
    41514349"getdefaulttimeout() -> timeout\n\
    41524350\n\
    4153 Returns the default timeout in floating seconds for new socket objects.\n\
     4351Returns the default timeout in seconds (float) for new socket objects.\n\
    41544352A value of None indicates that new socket objects have no timeout.\n\
    41554353When the socket module is first imported, the default is None.");
     
    41584356socket_setdefaulttimeout(PyObject *self, PyObject *arg)
    41594357{
    4160         double timeout;
    4161 
    4162         if (arg == Py_None)
    4163                 timeout = -1.0;
    4164         else {
    4165                 timeout = PyFloat_AsDouble(arg);
    4166                 if (timeout < 0.0) {
    4167                         if (!PyErr_Occurred())
    4168                                 PyErr_SetString(PyExc_ValueError,
    4169                                                 "Timeout value out of range");
    4170                         return NULL;
    4171                 }
    4172         }
    4173 
    4174         defaulttimeout = timeout;
    4175 
    4176         Py_INCREF(Py_None);
    4177         return Py_None;
     4358    double timeout;
     4359
     4360    if (arg == Py_None)
     4361        timeout = -1.0;
     4362    else {
     4363        timeout = PyFloat_AsDouble(arg);
     4364        if (timeout < 0.0) {
     4365            if (!PyErr_Occurred())
     4366                PyErr_SetString(PyExc_ValueError,
     4367                                "Timeout value out of range");
     4368            return NULL;
     4369        }
     4370    }
     4371
     4372    defaulttimeout = timeout;
     4373
     4374    Py_INCREF(Py_None);
     4375    return Py_None;
    41784376}
    41794377
     
    41814379"setdefaulttimeout(timeout)\n\
    41824380\n\
    4183 Set the default timeout in floating seconds for new socket objects.\n\
     4381Set the default timeout in seconds (float) for new socket objects.\n\
    41844382A value of None indicates that new socket objects have no timeout.\n\
    41854383When the socket module is first imported, the default is None.");
     
    41894387
    41904388static PyMethodDef socket_methods[] = {
    4191         {"gethostbyname",       socket_gethostbyname,
    4192         METH_VARARGS, gethostbyname_doc},
    4193         {"gethostbyname_ex",    socket_gethostbyname_ex,
    4194         METH_VARARGS, ghbn_ex_doc},
    4195         {"gethostbyaddr",       socket_gethostbyaddr,
    4196         METH_VARARGS, gethostbyaddr_doc},
    4197         {"gethostname",         socket_gethostname,
    4198         METH_NOARGS,  gethostname_doc},
    4199         {"getservbyname",       socket_getservbyname,
    4200         METH_VARARGS, getservbyname_doc},
    4201         {"getservbyport",       socket_getservbyport,
    4202         METH_VARARGS, getservbyport_doc},
    4203         {"getprotobyname",      socket_getprotobyname,
    4204         METH_VARARGS, getprotobyname_doc},
     4389    {"gethostbyname",           socket_gethostbyname,
     4390    METH_VARARGS, gethostbyname_doc},
     4391    {"gethostbyname_ex",        socket_gethostbyname_ex,
     4392    METH_VARARGS, ghbn_ex_doc},
     4393    {"gethostbyaddr",           socket_gethostbyaddr,
     4394    METH_VARARGS, gethostbyaddr_doc},
     4395    {"gethostname",             socket_gethostname,
     4396    METH_NOARGS,  gethostname_doc},
     4397    {"getservbyname",           socket_getservbyname,
     4398    METH_VARARGS, getservbyname_doc},
     4399    {"getservbyport",           socket_getservbyport,
     4400    METH_VARARGS, getservbyport_doc},
     4401    {"getprotobyname",          socket_getprotobyname,
     4402    METH_VARARGS, getprotobyname_doc},
    42054403#ifndef NO_DUP
    4206         {"fromfd",              socket_fromfd,
    4207         METH_VARARGS, fromfd_doc},
     4404    {"fromfd",                  socket_fromfd,
     4405    METH_VARARGS, fromfd_doc},
    42084406#endif
    42094407#ifdef HAVE_SOCKETPAIR
    4210         {"socketpair",          socket_socketpair,
    4211         METH_VARARGS, socketpair_doc},
    4212 #endif
    4213         {"ntohs",               socket_ntohs,
    4214         METH_VARARGS, ntohs_doc},
    4215         {"ntohl",               socket_ntohl,
    4216         METH_O, ntohl_doc},
    4217         {"htons",               socket_htons,
    4218         METH_VARARGS, htons_doc},
    4219         {"htonl",               socket_htonl,
    4220         METH_O, htonl_doc},
    4221         {"inet_aton",           socket_inet_aton,
    4222         METH_VARARGS, inet_aton_doc},
    4223         {"inet_ntoa",           socket_inet_ntoa,
    4224         METH_VARARGS, inet_ntoa_doc},
     4408    {"socketpair",              socket_socketpair,
     4409    METH_VARARGS, socketpair_doc},
     4410#endif
     4411    {"ntohs",                   socket_ntohs,
     4412    METH_VARARGS, ntohs_doc},
     4413    {"ntohl",                   socket_ntohl,
     4414    METH_O, ntohl_doc},
     4415    {"htons",                   socket_htons,
     4416    METH_VARARGS, htons_doc},
     4417    {"htonl",                   socket_htonl,
     4418    METH_O, htonl_doc},
     4419    {"inet_aton",               socket_inet_aton,
     4420    METH_VARARGS, inet_aton_doc},
     4421    {"inet_ntoa",               socket_inet_ntoa,
     4422    METH_VARARGS, inet_ntoa_doc},
    42254423#ifdef HAVE_INET_PTON
    4226         {"inet_pton",           socket_inet_pton,
    4227         METH_VARARGS, inet_pton_doc},
    4228         {"inet_ntop",           socket_inet_ntop,
    4229         METH_VARARGS, inet_ntop_doc},
    4230 #endif
    4231         {"getaddrinfo",         socket_getaddrinfo,
    4232         METH_VARARGS, getaddrinfo_doc},
    4233         {"getnameinfo",         socket_getnameinfo,
    4234         METH_VARARGS, getnameinfo_doc},
    4235         {"getdefaulttimeout",   (PyCFunction)socket_getdefaulttimeout,
    4236         METH_NOARGS, getdefaulttimeout_doc},
    4237         {"setdefaulttimeout",   socket_setdefaulttimeout,
    4238         METH_O, setdefaulttimeout_doc},
    4239         {NULL,                  NULL}            /* Sentinel */
     4424    {"inet_pton",               socket_inet_pton,
     4425    METH_VARARGS, inet_pton_doc},
     4426    {"inet_ntop",               socket_inet_ntop,
     4427    METH_VARARGS, inet_ntop_doc},
     4428#endif
     4429    {"getaddrinfo",             socket_getaddrinfo,
     4430    METH_VARARGS, getaddrinfo_doc},
     4431    {"getnameinfo",             socket_getnameinfo,
     4432    METH_VARARGS, getnameinfo_doc},
     4433    {"getdefaulttimeout",       (PyCFunction)socket_getdefaulttimeout,
     4434    METH_NOARGS, getdefaulttimeout_doc},
     4435    {"setdefaulttimeout",       socket_setdefaulttimeout,
     4436    METH_O, setdefaulttimeout_doc},
     4437    {NULL,                      NULL}            /* Sentinel */
    42404438};
    42414439
     
    42474445os_init(void)
    42484446{
    4249         _kernel_swi_regs r;
    4250 
    4251         r.r[0] = 0;
    4252         _kernel_swi(0x43380, &r, &r);
    4253         taskwindow = r.r[0];
    4254 
    4255         return 1;
     4447    _kernel_swi_regs r;
     4448
     4449    r.r[0] = 0;
     4450    _kernel_swi(0x43380, &r, &r);
     4451    taskwindow = r.r[0];
     4452
     4453    return 1;
    42564454}
    42574455
     
    42674465os_cleanup(void)
    42684466{
    4269         WSACleanup();
     4467    WSACleanup();
    42704468}
    42714469
     
    42734471os_init(void)
    42744472{
    4275         WSADATA WSAData;
    4276         int ret;
    4277         char buf[100];
    4278         ret = WSAStartup(0x0101, &WSAData);
    4279         switch (ret) {
    4280         case 0: /* No error */
    4281                 Py_AtExit(os_cleanup);
    4282                 return 1; /* Success */
    4283         case WSASYSNOTREADY:
    4284                 PyErr_SetString(PyExc_ImportError,
    4285                                 "WSAStartup failed: network not ready");
    4286                 break;
    4287         case WSAVERNOTSUPPORTED:
    4288         case WSAEINVAL:
    4289                 PyErr_SetString(
    4290                         PyExc_ImportError,
    4291                         "WSAStartup failed: requested version not supported");
    4292                 break;
    4293         default:
    4294                 PyOS_snprintf(buf, sizeof(buf),
    4295                               "WSAStartup failed: error code %d", ret);
    4296                 PyErr_SetString(PyExc_ImportError, buf);
    4297                 break;
    4298         }
    4299         return 0; /* Failure */
     4473    WSADATA WSAData;
     4474    int ret;
     4475    char buf[100];
     4476    ret = WSAStartup(0x0101, &WSAData);
     4477    switch (ret) {
     4478    case 0:     /* No error */
     4479        Py_AtExit(os_cleanup);
     4480        return 1; /* Success */
     4481    case WSASYSNOTREADY:
     4482        PyErr_SetString(PyExc_ImportError,
     4483                        "WSAStartup failed: network not ready");
     4484        break;
     4485    case WSAVERNOTSUPPORTED:
     4486    case WSAEINVAL:
     4487        PyErr_SetString(
     4488            PyExc_ImportError,
     4489            "WSAStartup failed: requested version not supported");
     4490        break;
     4491    default:
     4492        PyOS_snprintf(buf, sizeof(buf),
     4493                      "WSAStartup failed: error code %d", ret);
     4494        PyErr_SetString(PyExc_ImportError, buf);
     4495        break;
     4496    }
     4497    return 0; /* Failure */
    43004498}
    43014499
     
    43124510{
    43134511#ifndef PYCC_GCC
    4314         char reason[64];
    4315         int rc = sock_init();
    4316 
    4317         if (rc == 0) {
    4318                 return 1; /* Success */
    4319         }
    4320 
    4321         PyOS_snprintf(reason, sizeof(reason),
    4322                       "OS/2 TCP/IP Error# %d", sock_errno());
    4323         PyErr_SetString(PyExc_ImportError, reason);
    4324 
    4325         return 0;  /* Failure */
    4326 #else
    4327         /* No need to initialise sockets with GCC/EMX */
    4328         return 1; /* Success */
     4512    char reason[64];
     4513    int rc = sock_init();
     4514
     4515    if (rc == 0) {
     4516        return 1; /* Success */
     4517    }
     4518
     4519    PyOS_snprintf(reason, sizeof(reason),
     4520                  "OS/2 TCP/IP Error# %d", sock_errno());
     4521    PyErr_SetString(PyExc_ImportError, reason);
     4522
     4523    return 0;  /* Failure */
     4524#else
     4525    /* No need to initialize sockets with GCC/EMX */
     4526    return 1; /* Success */
    43294527#endif
    43304528}
     
    43374535os_init(void)
    43384536{
    4339         return 1; /* Success */
     4537    return 1; /* Success */
    43404538}
    43414539#endif
     
    43474545PySocketModule_APIObject PySocketModuleAPI =
    43484546{
    4349         &sock_type,
    4350         NULL
     4547    &sock_type,
     4548    NULL
    43514549};
    43524550
     
    43614559   with an ImportError exception if os-specific initialization fails.
    43624560   On Windows, this does WINSOCK initialization.  When WINSOCK is
    4363    initialized succesfully, a call to WSACleanup() is scheduled to be
     4561   initialized successfully, a call to WSACleanup() is scheduled to be
    43644562   made at exit time.
    43654563*/
     
    43734571init_socket(void)
    43744572{
    4375         PyObject *m, *has_ipv6;
    4376 
    4377         if (!os_init())
    4378                 return;
    4379 
    4380         Py_TYPE(&sock_type) = &PyType_Type;
    4381         m = Py_InitModule3(PySocket_MODULE_NAME,
    4382                            socket_methods,
    4383                            socket_doc);
    4384         if (m == NULL)
    4385                 return;
    4386 
    4387         socket_error = PyErr_NewException("socket.error",
    4388                                           PyExc_IOError, NULL);
    4389         if (socket_error == NULL)
    4390                 return;
    4391         PySocketModuleAPI.error = socket_error;
    4392         Py_INCREF(socket_error);
    4393         PyModule_AddObject(m, "error", socket_error);
    4394         socket_herror = PyErr_NewException("socket.herror",
    4395                                            socket_error, NULL);
    4396         if (socket_herror == NULL)
    4397                 return;
    4398         Py_INCREF(socket_herror);
    4399         PyModule_AddObject(m, "herror", socket_herror);
    4400         socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
    4401             NULL);
    4402         if (socket_gaierror == NULL)
    4403                 return;
    4404         Py_INCREF(socket_gaierror);
    4405         PyModule_AddObject(m, "gaierror", socket_gaierror);
    4406         socket_timeout = PyErr_NewException("socket.timeout",
    4407                                             socket_error, NULL);
    4408         if (socket_timeout == NULL)
    4409                 return;
    4410         Py_INCREF(socket_timeout);
    4411         PyModule_AddObject(m, "timeout", socket_timeout);
    4412         Py_INCREF((PyObject *)&sock_type);
    4413         if (PyModule_AddObject(m, "SocketType",
    4414                                (PyObject *)&sock_type) != 0)
    4415                 return;
    4416         Py_INCREF((PyObject *)&sock_type);
    4417         if (PyModule_AddObject(m, "socket",
    4418                                (PyObject *)&sock_type) != 0)
    4419                 return;
     4573    PyObject *m, *has_ipv6;
     4574
     4575    if (!os_init())
     4576        return;
     4577
     4578    Py_TYPE(&sock_type) = &PyType_Type;
     4579    m = Py_InitModule3(PySocket_MODULE_NAME,
     4580                       socket_methods,
     4581                       socket_doc);
     4582    if (m == NULL)
     4583        return;
     4584
     4585    socket_error = PyErr_NewException("socket.error",
     4586                                      PyExc_IOError, NULL);
     4587    if (socket_error == NULL)
     4588        return;
     4589    PySocketModuleAPI.error = socket_error;
     4590    Py_INCREF(socket_error);
     4591    PyModule_AddObject(m, "error", socket_error);
     4592    socket_herror = PyErr_NewException("socket.herror",
     4593                                       socket_error, NULL);
     4594    if (socket_herror == NULL)
     4595        return;
     4596    Py_INCREF(socket_herror);
     4597    PyModule_AddObject(m, "herror", socket_herror);
     4598    socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
     4599        NULL);
     4600    if (socket_gaierror == NULL)
     4601        return;
     4602    Py_INCREF(socket_gaierror);
     4603    PyModule_AddObject(m, "gaierror", socket_gaierror);
     4604    socket_timeout = PyErr_NewException("socket.timeout",
     4605                                        socket_error, NULL);
     4606    if (socket_timeout == NULL)
     4607        return;
     4608    Py_INCREF(socket_timeout);
     4609    PyModule_AddObject(m, "timeout", socket_timeout);
     4610    Py_INCREF((PyObject *)&sock_type);
     4611    if (PyModule_AddObject(m, "SocketType",
     4612                           (PyObject *)&sock_type) != 0)
     4613        return;
     4614    Py_INCREF((PyObject *)&sock_type);
     4615    if (PyModule_AddObject(m, "socket",
     4616                           (PyObject *)&sock_type) != 0)
     4617        return;
    44204618
    44214619#ifdef ENABLE_IPV6
    4422         has_ipv6 = Py_True;
    4423 #else
    4424         has_ipv6 = Py_False;
    4425 #endif
    4426         Py_INCREF(has_ipv6);
    4427         PyModule_AddObject(m, "has_ipv6", has_ipv6);
    4428 
    4429         /* Export C API */
    4430         if (PyModule_AddObject(m, PySocket_CAPI_NAME,
    4431                PyCObject_FromVoidPtr((void *)&PySocketModuleAPI, NULL)
    4432                                 ) != 0)
    4433                 return;
    4434 
    4435         /* Address families (we only support AF_INET and AF_UNIX) */
     4620    has_ipv6 = Py_True;
     4621#else
     4622    has_ipv6 = Py_False;
     4623#endif
     4624    Py_INCREF(has_ipv6);
     4625    PyModule_AddObject(m, "has_ipv6", has_ipv6);
     4626
     4627    /* Export C API */
     4628    if (PyModule_AddObject(m, PySocket_CAPI_NAME,
     4629           PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL)
     4630                            ) != 0)
     4631        return;
     4632
     4633    /* Address families (we only support AF_INET and AF_UNIX) */
    44364634#ifdef AF_UNSPEC
    4437         PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
    4438 #endif
    4439         PyModule_AddIntConstant(m, "AF_INET", AF_INET);
     4635    PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
     4636#endif
     4637    PyModule_AddIntConstant(m, "AF_INET", AF_INET);
    44404638#ifdef AF_INET6
    4441         PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
     4639    PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
    44424640#endif /* AF_INET6 */
    44434641#if defined(AF_UNIX)
    4444         PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
     4642    PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
    44454643#endif /* AF_UNIX */
    44464644#ifdef AF_AX25
    4447         /* Amateur Radio AX.25 */
    4448         PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
     4645    /* Amateur Radio AX.25 */
     4646    PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
    44494647#endif
    44504648#ifdef AF_IPX
    4451         PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
     4649    PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
    44524650#endif
    44534651#ifdef AF_APPLETALK
    4454         /* Appletalk DDP */
    4455         PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
     4652    /* Appletalk DDP */
     4653    PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
    44564654#endif
    44574655#ifdef AF_NETROM
    4458         /* Amateur radio NetROM */
    4459         PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
     4656    /* Amateur radio NetROM */
     4657    PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
    44604658#endif
    44614659#ifdef AF_BRIDGE
    4462         /* Multiprotocol bridge */
    4463         PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
     4660    /* Multiprotocol bridge */
     4661    PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
    44644662#endif
    44654663#ifdef AF_ATMPVC
    4466         /* ATM PVCs */
    4467         PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
     4664    /* ATM PVCs */
     4665    PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
    44684666#endif
    44694667#ifdef AF_AAL5
    4470         /* Reserved for Werner's ATM */
    4471         PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
     4668    /* Reserved for Werner's ATM */
     4669    PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
    44724670#endif
    44734671#ifdef AF_X25
    4474         /* Reserved for X.25 project */
    4475         PyModule_AddIntConstant(m, "AF_X25", AF_X25);
     4672    /* Reserved for X.25 project */
     4673    PyModule_AddIntConstant(m, "AF_X25", AF_X25);
    44764674#endif
    44774675#ifdef AF_INET6
    4478         PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
     4676    PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
    44794677#endif
    44804678#ifdef AF_ROSE
    4481         /* Amateur Radio X.25 PLP */
    4482         PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
     4679    /* Amateur Radio X.25 PLP */
     4680    PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
    44834681#endif
    44844682#ifdef AF_DECnet
    4485         /* Reserved for DECnet project */
    4486         PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
     4683    /* Reserved for DECnet project */
     4684    PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
    44874685#endif
    44884686#ifdef AF_NETBEUI
    4489         /* Reserved for 802.2LLC project */
    4490         PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
     4687    /* Reserved for 802.2LLC project */
     4688    PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
    44914689#endif
    44924690#ifdef AF_SECURITY
    4493         /* Security callback pseudo AF */
    4494         PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
     4691    /* Security callback pseudo AF */
     4692    PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
    44954693#endif
    44964694#ifdef AF_KEY
    4497         /* PF_KEY key management API */
    4498         PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
     4695    /* PF_KEY key management API */
     4696    PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
    44994697#endif
    45004698#ifdef AF_NETLINK
    4501         /*  */
    4502         PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
    4503         PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
     4699    /*  */
     4700    PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
     4701    PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
    45044702#ifdef NETLINK_SKIP
    4505         PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
     4703    PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
    45064704#endif
    45074705#ifdef NETLINK_W1
    4508         PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
    4509 #endif
    4510         PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
    4511         PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
     4706    PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
     4707#endif
     4708    PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
     4709    PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
    45124710#ifdef NETLINK_TCPDIAG
    4513         PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
     4711    PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
    45144712#endif
    45154713#ifdef NETLINK_NFLOG
    4516         PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
     4714    PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
    45174715#endif
    45184716#ifdef NETLINK_XFRM
    4519         PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
     4717    PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
    45204718#endif
    45214719#ifdef NETLINK_ARPD
    4522         PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
     4720    PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
    45234721#endif
    45244722#ifdef NETLINK_ROUTE6
    4525         PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
    4526 #endif
    4527         PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
     4723    PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
     4724#endif
     4725    PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
    45284726#ifdef NETLINK_DNRTMSG
    4529         PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
    4530 #endif 
     4727    PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
     4728#endif
    45314729#ifdef NETLINK_TAPBASE
    4532         PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
     4730    PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
    45334731#endif
    45344732#endif /* AF_NETLINK */
    45354733#ifdef AF_ROUTE
    4536         /* Alias to emulate 4.4BSD */
    4537         PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
     4734    /* Alias to emulate 4.4BSD */
     4735    PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
    45384736#endif
    45394737#ifdef AF_ASH
    4540         /* Ash */
    4541         PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
     4738    /* Ash */
     4739    PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
    45424740#endif
    45434741#ifdef AF_ECONET
    4544         /* Acorn Econet */
    4545         PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
     4742    /* Acorn Econet */
     4743    PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
    45464744#endif
    45474745#ifdef AF_ATMSVC
    4548         /* ATM SVCs */
    4549         PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
     4746    /* ATM SVCs */
     4747    PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
    45504748#endif
    45514749#ifdef AF_SNA
    4552         /* Linux SNA Project (nutters!) */
    4553         PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
     4750    /* Linux SNA Project (nutters!) */
     4751    PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
    45544752#endif
    45554753#ifdef AF_IRDA
    4556         /* IRDA sockets */
    4557         PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
     4754    /* IRDA sockets */
     4755    PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
    45584756#endif
    45594757#ifdef AF_PPPOX
    4560         /* PPPoX sockets */
    4561         PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
     4758    /* PPPoX sockets */
     4759    PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
    45624760#endif
    45634761#ifdef AF_WANPIPE
    4564         /* Wanpipe API Sockets */
    4565         PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
     4762    /* Wanpipe API Sockets */
     4763    PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
    45664764#endif
    45674765#ifdef AF_LLC
    4568         /* Linux LLC */
    4569         PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
     4766    /* Linux LLC */
     4767    PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
    45704768#endif
    45714769
    45724770#ifdef USE_BLUETOOTH
    4573         PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
    4574         PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
    4575         PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
    4576         PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
    4577         PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
     4771    PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
     4772    PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
     4773    PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
     4774    PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
     4775#if !defined(__NetBSD__) && !defined(__DragonFly__)
     4776    PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
     4777#endif
    45784778#if !defined(__FreeBSD__)
    4579         PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
    4580         PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
    4581         PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
    4582 #endif
    4583         PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
    4584         PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
    4585         PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
    4586 #endif
    4587 
    4588 #ifdef HAVE_NETPACKET_PACKET_H
    4589         PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
    4590         PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
    4591         PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
    4592         PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
    4593         PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
    4594         PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
    4595         PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
    4596         PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
    4597         PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
     4779#if !defined(__NetBSD__) && !defined(__DragonFly__)
     4780    PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
     4781#endif
     4782    PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
     4783    PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
     4784#endif
     4785    PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
     4786    PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
     4787    PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
     4788#endif
     4789
     4790#ifdef AF_PACKET
     4791    PyModule_AddIntMacro(m, AF_PACKET);
     4792#endif
     4793#ifdef PF_PACKET
     4794    PyModule_AddIntMacro(m, PF_PACKET);
     4795#endif
     4796#ifdef PACKET_HOST
     4797    PyModule_AddIntMacro(m, PACKET_HOST);
     4798#endif
     4799#ifdef PACKET_BROADCAST
     4800    PyModule_AddIntMacro(m, PACKET_BROADCAST);
     4801#endif
     4802#ifdef PACKET_MULTICAST
     4803    PyModule_AddIntMacro(m, PACKET_MULTICAST);
     4804#endif
     4805#ifdef PACKET_OTHERHOST
     4806    PyModule_AddIntMacro(m, PACKET_OTHERHOST);
     4807#endif
     4808#ifdef PACKET_OUTGOING
     4809    PyModule_AddIntMacro(m, PACKET_OUTGOING);
     4810#endif
     4811#ifdef PACKET_LOOPBACK
     4812    PyModule_AddIntMacro(m, PACKET_LOOPBACK);
     4813#endif
     4814#ifdef PACKET_FASTROUTE
     4815    PyModule_AddIntMacro(m, PACKET_FASTROUTE);
    45984816#endif
    45994817
    46004818#ifdef HAVE_LINUX_TIPC_H
    4601         PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC);
    4602 
    4603         /* for addresses */
    4604         PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ);
    4605         PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME);
    4606         PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID);
    4607 
    4608         PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE);
    4609         PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE);
    4610         PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE);
    4611 
    4612         /* for setsockopt() */
    4613         PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC);
    4614         PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE);
    4615         PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE);
    4616         PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE",
    4617                         TIPC_DEST_DROPPABLE);
    4618         PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT);
    4619 
    4620         PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE",
    4621                         TIPC_LOW_IMPORTANCE);
    4622         PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE",
    4623                         TIPC_MEDIUM_IMPORTANCE);
    4624         PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE",
    4625                         TIPC_HIGH_IMPORTANCE);
    4626         PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE",
    4627                         TIPC_CRITICAL_IMPORTANCE);
    4628 
    4629         /* for subscriptions */
    4630         PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS);
    4631         PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE);
     4819    PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC);
     4820
     4821    /* for addresses */
     4822    PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ);
     4823    PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME);
     4824    PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID);
     4825
     4826    PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE);
     4827    PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE);
     4828    PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE);
     4829
     4830    /* for setsockopt() */
     4831    PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC);
     4832    PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE);
     4833    PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE);
     4834    PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE",
     4835                    TIPC_DEST_DROPPABLE);
     4836    PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT);
     4837
     4838    PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE",
     4839                    TIPC_LOW_IMPORTANCE);
     4840    PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE",
     4841                    TIPC_MEDIUM_IMPORTANCE);
     4842    PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE",
     4843                    TIPC_HIGH_IMPORTANCE);
     4844    PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE",
     4845                    TIPC_CRITICAL_IMPORTANCE);
     4846
     4847    /* for subscriptions */
     4848    PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS);
     4849    PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE);
    46324850#ifdef TIPC_SUB_CANCEL
    4633         /* doesn't seem to be available everywhere */
    4634         PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL);
    4635 #endif
    4636         PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER);
    4637         PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED);
    4638         PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN);
    4639         PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT);
    4640         PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV);
    4641         PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV);
    4642 #endif
    4643 
    4644         /* Socket types */
    4645         PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
    4646         PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
     4851    /* doesn't seem to be available everywhere */
     4852    PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL);
     4853#endif
     4854    PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER);
     4855    PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED);
     4856    PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN);
     4857    PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT);
     4858    PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV);
     4859    PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV);
     4860#endif
     4861
     4862    /* Socket types */
     4863    PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
     4864    PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
    46474865#ifndef __BEOS__
    46484866/* We have incomplete socket support. */
    4649         PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
    4650         PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
     4867    PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
     4868    PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
    46514869#if defined(SOCK_RDM)
    4652         PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
    4653 #endif
    4654 #endif
    4655 
    4656 #ifdef  SO_DEBUG
    4657         PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
    4658 #endif
    4659 #ifdef  SO_ACCEPTCONN
    4660         PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
    4661 #endif
    4662 #ifdef  SO_REUSEADDR
    4663         PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
     4870    PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
     4871#endif
     4872#endif
     4873
     4874#ifdef  SO_DEBUG
     4875    PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
     4876#endif
     4877#ifdef  SO_ACCEPTCONN
     4878    PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
     4879#endif
     4880#ifdef  SO_REUSEADDR
     4881    PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
    46644882#endif
    46654883#ifdef SO_EXCLUSIVEADDRUSE
    4666         PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
    4667 #endif
    4668 
    4669 #ifdef  SO_KEEPALIVE
    4670         PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
    4671 #endif
    4672 #ifdef  SO_DONTROUTE
    4673         PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
    4674 #endif
    4675 #ifdef  SO_BROADCAST
    4676         PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
    4677 #endif
    4678 #ifdef  SO_USELOOPBACK
    4679         PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
    4680 #endif
    4681 #ifdef  SO_LINGER
    4682         PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
    4683 #endif
    4684 #ifdef  SO_OOBINLINE
    4685         PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
    4686 #endif
    4687 #ifdef  SO_REUSEPORT
    4688         PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
    4689 #endif
    4690 #ifdef  SO_SNDBUF
    4691         PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
    4692 #endif
    4693 #ifdef  SO_RCVBUF
    4694         PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
    4695 #endif
    4696 #ifdef  SO_SNDLOWAT
    4697         PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
    4698 #endif
    4699 #ifdef  SO_RCVLOWAT
    4700         PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
    4701 #endif
    4702 #ifdef  SO_SNDTIMEO
    4703         PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
    4704 #endif
    4705 #ifdef  SO_RCVTIMEO
    4706         PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
    4707 #endif
    4708 #ifdef  SO_ERROR
    4709         PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
    4710 #endif
    4711 #ifdef  SO_TYPE
    4712         PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
    4713 #endif
    4714 
    4715         /* Maximum number of connections for "listen" */
    4716 #ifdef  SOMAXCONN
    4717         PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
    4718 #else
    4719         PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
    4720 #endif
    4721 
    4722         /* Flags for send, recv */
    4723 #ifdef  MSG_OOB
    4724         PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
    4725 #endif
    4726 #ifdef  MSG_PEEK
    4727         PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
    4728 #endif
    4729 #ifdef  MSG_DONTROUTE
    4730         PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
    4731 #endif
    4732 #ifdef  MSG_DONTWAIT
    4733         PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
    4734 #endif
    4735 #ifdef  MSG_EOR
    4736         PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
    4737 #endif
    4738 #ifdef  MSG_TRUNC
    4739         PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
    4740 #endif
    4741 #ifdef  MSG_CTRUNC
    4742         PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
    4743 #endif
    4744 #ifdef  MSG_WAITALL
    4745         PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
    4746 #endif
    4747 #ifdef  MSG_BTAG
    4748         PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
    4749 #endif
    4750 #ifdef  MSG_ETAG
    4751         PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
    4752 #endif
    4753 
    4754         /* Protocol level and numbers, usable for [gs]etsockopt */
    4755 #ifdef  SOL_SOCKET
    4756         PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
    4757 #endif
    4758 #ifdef  SOL_IP
    4759         PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
    4760 #else
    4761         PyModule_AddIntConstant(m, "SOL_IP", 0);
    4762 #endif
    4763 #ifdef  SOL_IPX
    4764         PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
    4765 #endif
    4766 #ifdef  SOL_AX25
    4767         PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
    4768 #endif
    4769 #ifdef  SOL_ATALK
    4770         PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
    4771 #endif
    4772 #ifdef  SOL_NETROM
    4773         PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
    4774 #endif
    4775 #ifdef  SOL_ROSE
    4776         PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
    4777 #endif
    4778 #ifdef  SOL_TCP
    4779         PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
    4780 #else
    4781         PyModule_AddIntConstant(m, "SOL_TCP", 6);
    4782 #endif
    4783 #ifdef  SOL_UDP
    4784         PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
    4785 #else
    4786         PyModule_AddIntConstant(m, "SOL_UDP", 17);
    4787 #endif
    4788 #ifdef  IPPROTO_IP
    4789         PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
    4790 #else
    4791         PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
    4792 #endif
    4793 #ifdef  IPPROTO_HOPOPTS
    4794         PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
    4795 #endif
    4796 #ifdef  IPPROTO_ICMP
    4797         PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
    4798 #else
    4799         PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
    4800 #endif
    4801 #ifdef  IPPROTO_IGMP
    4802         PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
    4803 #endif
    4804 #ifdef  IPPROTO_GGP
    4805         PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
    4806 #endif
    4807 #ifdef  IPPROTO_IPV4
    4808         PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
    4809 #endif
    4810 #ifdef  IPPROTO_IPV6
    4811         PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
    4812 #endif
    4813 #ifdef  IPPROTO_IPIP
    4814         PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
    4815 #endif
    4816 #ifdef  IPPROTO_TCP
    4817         PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
    4818 #else
    4819         PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
    4820 #endif
    4821 #ifdef  IPPROTO_EGP
    4822         PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
    4823 #endif
    4824 #ifdef  IPPROTO_PUP
    4825         PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
    4826 #endif
    4827 #ifdef  IPPROTO_UDP
    4828         PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
    4829 #else
    4830         PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
    4831 #endif
    4832 #ifdef  IPPROTO_IDP
    4833         PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
    4834 #endif
    4835 #ifdef  IPPROTO_HELLO
    4836         PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
    4837 #endif
    4838 #ifdef  IPPROTO_ND
    4839         PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
    4840 #endif
    4841 #ifdef  IPPROTO_TP
    4842         PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
    4843 #endif
    4844 #ifdef  IPPROTO_IPV6
    4845         PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
    4846 #endif
    4847 #ifdef  IPPROTO_ROUTING
    4848         PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
    4849 #endif
    4850 #ifdef  IPPROTO_FRAGMENT
    4851         PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
    4852 #endif
    4853 #ifdef  IPPROTO_RSVP
    4854         PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
    4855 #endif
    4856 #ifdef  IPPROTO_GRE
    4857         PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
    4858 #endif
    4859 #ifdef  IPPROTO_ESP
    4860         PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
    4861 #endif
    4862 #ifdef  IPPROTO_AH
    4863         PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
    4864 #endif
    4865 #ifdef  IPPROTO_MOBILE
    4866         PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
    4867 #endif
    4868 #ifdef  IPPROTO_ICMPV6
    4869         PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
    4870 #endif
    4871 #ifdef  IPPROTO_NONE
    4872         PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
    4873 #endif
    4874 #ifdef  IPPROTO_DSTOPTS
    4875         PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
    4876 #endif
    4877 #ifdef  IPPROTO_XTP
    4878         PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
    4879 #endif
    4880 #ifdef  IPPROTO_EON
    4881         PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
    4882 #endif
    4883 #ifdef  IPPROTO_PIM
    4884         PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
    4885 #endif
    4886 #ifdef  IPPROTO_IPCOMP
    4887         PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
    4888 #endif
    4889 #ifdef  IPPROTO_VRRP
    4890         PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
    4891 #endif
    4892 #ifdef  IPPROTO_BIP
    4893         PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
     4884    PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
     4885#endif
     4886
     4887#ifdef  SO_KEEPALIVE
     4888    PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
     4889#endif
     4890#ifdef  SO_DONTROUTE
     4891    PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
     4892#endif
     4893#ifdef  SO_BROADCAST
     4894    PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
     4895#endif
     4896#ifdef  SO_USELOOPBACK
     4897    PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
     4898#endif
     4899#ifdef  SO_LINGER
     4900    PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
     4901#endif
     4902#ifdef  SO_OOBINLINE
     4903    PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
     4904#endif
     4905#ifdef  SO_REUSEPORT
     4906    PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
     4907#endif
     4908#ifdef  SO_SNDBUF
     4909    PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
     4910#endif
     4911#ifdef  SO_RCVBUF
     4912    PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
     4913#endif
     4914#ifdef  SO_SNDLOWAT
     4915    PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
     4916#endif
     4917#ifdef  SO_RCVLOWAT
     4918    PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
     4919#endif
     4920#ifdef  SO_SNDTIMEO
     4921    PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
     4922#endif
     4923#ifdef  SO_RCVTIMEO
     4924    PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
     4925#endif
     4926#ifdef  SO_ERROR
     4927    PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
     4928#endif
     4929#ifdef  SO_TYPE
     4930    PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
     4931#endif
     4932#ifdef SO_SETFIB
     4933    PyModule_AddIntConstant(m, "SO_SETFIB", SO_SETFIB);
     4934#endif
     4935
     4936    /* Maximum number of connections for "listen" */
     4937#ifdef  SOMAXCONN
     4938    PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
     4939#else
     4940    PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
     4941#endif
     4942
     4943    /* Flags for send, recv */
     4944#ifdef  MSG_OOB
     4945    PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
     4946#endif
     4947#ifdef  MSG_PEEK
     4948    PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
     4949#endif
     4950#ifdef  MSG_DONTROUTE
     4951    PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
     4952#endif
     4953#ifdef  MSG_DONTWAIT
     4954    PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
     4955#endif
     4956#ifdef  MSG_EOR
     4957    PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
     4958#endif
     4959#ifdef  MSG_TRUNC
     4960    PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
     4961#endif
     4962#ifdef  MSG_CTRUNC
     4963    PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
     4964#endif
     4965#ifdef  MSG_WAITALL
     4966    PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
     4967#endif
     4968#ifdef  MSG_BTAG
     4969    PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
     4970#endif
     4971#ifdef  MSG_ETAG
     4972    PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
     4973#endif
     4974
     4975    /* Protocol level and numbers, usable for [gs]etsockopt */
     4976#ifdef  SOL_SOCKET
     4977    PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
     4978#endif
     4979#ifdef  SOL_IP
     4980    PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
     4981#else
     4982    PyModule_AddIntConstant(m, "SOL_IP", 0);
     4983#endif
     4984#ifdef  SOL_IPX
     4985    PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
     4986#endif
     4987#ifdef  SOL_AX25
     4988    PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
     4989#endif
     4990#ifdef  SOL_ATALK
     4991    PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
     4992#endif
     4993#ifdef  SOL_NETROM
     4994    PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
     4995#endif
     4996#ifdef  SOL_ROSE
     4997    PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
     4998#endif
     4999#ifdef  SOL_TCP
     5000    PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
     5001#else
     5002    PyModule_AddIntConstant(m, "SOL_TCP", 6);
     5003#endif
     5004#ifdef  SOL_UDP
     5005    PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
     5006#else
     5007    PyModule_AddIntConstant(m, "SOL_UDP", 17);
     5008#endif
     5009#ifdef  IPPROTO_IP
     5010    PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
     5011#else
     5012    PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
     5013#endif
     5014#ifdef  IPPROTO_HOPOPTS
     5015    PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
     5016#endif
     5017#ifdef  IPPROTO_ICMP
     5018    PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
     5019#else
     5020    PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
     5021#endif
     5022#ifdef  IPPROTO_IGMP
     5023    PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
     5024#endif
     5025#ifdef  IPPROTO_GGP
     5026    PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
     5027#endif
     5028#ifdef  IPPROTO_IPV4
     5029    PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
     5030#endif
     5031#ifdef  IPPROTO_IPV6
     5032    PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
     5033#endif
     5034#ifdef  IPPROTO_IPIP
     5035    PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
     5036#endif
     5037#ifdef  IPPROTO_TCP
     5038    PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
     5039#else
     5040    PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
     5041#endif
     5042#ifdef  IPPROTO_EGP
     5043    PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
     5044#endif
     5045#ifdef  IPPROTO_PUP
     5046    PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
     5047#endif
     5048#ifdef  IPPROTO_UDP
     5049    PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
     5050#else
     5051    PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
     5052#endif
     5053#ifdef  IPPROTO_IDP
     5054    PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
     5055#endif
     5056#ifdef  IPPROTO_HELLO
     5057    PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
     5058#endif
     5059#ifdef  IPPROTO_ND
     5060    PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
     5061#endif
     5062#ifdef  IPPROTO_TP
     5063    PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
     5064#endif
     5065#ifdef  IPPROTO_IPV6
     5066    PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
     5067#endif
     5068#ifdef  IPPROTO_ROUTING
     5069    PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
     5070#endif
     5071#ifdef  IPPROTO_FRAGMENT
     5072    PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
     5073#endif
     5074#ifdef  IPPROTO_RSVP
     5075    PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
     5076#endif
     5077#ifdef  IPPROTO_GRE
     5078    PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
     5079#endif
     5080#ifdef  IPPROTO_ESP
     5081    PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
     5082#endif
     5083#ifdef  IPPROTO_AH
     5084    PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
     5085#endif
     5086#ifdef  IPPROTO_MOBILE
     5087    PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
     5088#endif
     5089#ifdef  IPPROTO_ICMPV6
     5090    PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
     5091#endif
     5092#ifdef  IPPROTO_NONE
     5093    PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
     5094#endif
     5095#ifdef  IPPROTO_DSTOPTS
     5096    PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
     5097#endif
     5098#ifdef  IPPROTO_XTP
     5099    PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
     5100#endif
     5101#ifdef  IPPROTO_EON
     5102    PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
     5103#endif
     5104#ifdef  IPPROTO_PIM
     5105    PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
     5106#endif
     5107#ifdef  IPPROTO_IPCOMP
     5108    PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
     5109#endif
     5110#ifdef  IPPROTO_VRRP
     5111    PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
     5112#endif
     5113#ifdef  IPPROTO_BIP
     5114    PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
    48945115#endif
    48955116/**/
    4896 #ifdef  IPPROTO_RAW
    4897         PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
    4898 #else
    4899         PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
    4900 #endif
    4901 #ifdef  IPPROTO_MAX
    4902         PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
    4903 #endif
    4904 
    4905         /* Some port configuration */
    4906 #ifdef  IPPORT_RESERVED
    4907         PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
    4908 #else
    4909         PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
    4910 #endif
    4911 #ifdef  IPPORT_USERRESERVED
    4912         PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
    4913 #else
    4914         PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
    4915 #endif
    4916 
    4917         /* Some reserved IP v.4 addresses */
    4918 #ifdef  INADDR_ANY
    4919         PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
    4920 #else
    4921         PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
    4922 #endif
    4923 #ifdef  INADDR_BROADCAST
    4924         PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
    4925 #else
    4926         PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
    4927 #endif
    4928 #ifdef  INADDR_LOOPBACK
    4929         PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
    4930 #else
    4931         PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
    4932 #endif
    4933 #ifdef  INADDR_UNSPEC_GROUP
    4934         PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
    4935 #else
    4936         PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
    4937 #endif
    4938 #ifdef  INADDR_ALLHOSTS_GROUP
    4939         PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
    4940                                 INADDR_ALLHOSTS_GROUP);
    4941 #else
    4942         PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
    4943 #endif
    4944 #ifdef  INADDR_MAX_LOCAL_GROUP
    4945         PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
    4946                                 INADDR_MAX_LOCAL_GROUP);
    4947 #else
    4948         PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
    4949 #endif
    4950 #ifdef  INADDR_NONE
    4951         PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
    4952 #else
    4953         PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
    4954 #endif
    4955 
    4956         /* IPv4 [gs]etsockopt options */
    4957 #ifdef  IP_OPTIONS
    4958         PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
    4959 #endif
    4960 #ifdef  IP_HDRINCL
    4961         PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
    4962 #endif
    4963 #ifdef  IP_TOS
    4964         PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
    4965 #endif
    4966 #ifdef  IP_TTL
    4967         PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
    4968 #endif
    4969 #ifdef  IP_RECVOPTS
    4970         PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
    4971 #endif
    4972 #ifdef  IP_RECVRETOPTS
    4973         PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
    4974 #endif
    4975 #ifdef  IP_RECVDSTADDR
    4976         PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
    4977 #endif
    4978 #ifdef  IP_RETOPTS
    4979         PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
    4980 #endif
    4981 #ifdef  IP_MULTICAST_IF
    4982         PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
    4983 #endif
    4984 #ifdef  IP_MULTICAST_TTL
    4985         PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
    4986 #endif
    4987 #ifdef  IP_MULTICAST_LOOP
    4988         PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
    4989 #endif
    4990 #ifdef  IP_ADD_MEMBERSHIP
    4991         PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
    4992 #endif
    4993 #ifdef  IP_DROP_MEMBERSHIP
    4994         PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
    4995 #endif
    4996 #ifdef  IP_DEFAULT_MULTICAST_TTL
    4997         PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
    4998                                 IP_DEFAULT_MULTICAST_TTL);
    4999 #endif
    5000 #ifdef  IP_DEFAULT_MULTICAST_LOOP
    5001         PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
    5002                                 IP_DEFAULT_MULTICAST_LOOP);
    5003 #endif
    5004 #ifdef  IP_MAX_MEMBERSHIPS
    5005         PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
    5006 #endif
    5007 
    5008         /* IPv6 [gs]etsockopt options, defined in RFC2553 */
    5009 #ifdef  IPV6_JOIN_GROUP
    5010         PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
    5011 #endif
    5012 #ifdef  IPV6_LEAVE_GROUP
    5013         PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
    5014 #endif
    5015 #ifdef  IPV6_MULTICAST_HOPS
    5016         PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
    5017 #endif
    5018 #ifdef  IPV6_MULTICAST_IF
    5019         PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
    5020 #endif
    5021 #ifdef  IPV6_MULTICAST_LOOP
    5022         PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
    5023 #endif
    5024 #ifdef  IPV6_UNICAST_HOPS
    5025         PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
    5026 #endif
    5027         /* Additional IPV6 socket options, defined in RFC 3493 */
     5117#ifdef  IPPROTO_RAW
     5118    PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
     5119#else
     5120    PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
     5121#endif
     5122#ifdef  IPPROTO_MAX
     5123    PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
     5124#endif
     5125
     5126    /* Some port configuration */
     5127#ifdef  IPPORT_RESERVED
     5128    PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
     5129#else
     5130    PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
     5131#endif
     5132#ifdef  IPPORT_USERRESERVED
     5133    PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
     5134#else
     5135    PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
     5136#endif
     5137
     5138    /* Some reserved IP v.4 addresses */
     5139#ifdef  INADDR_ANY
     5140    PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
     5141#else
     5142    PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
     5143#endif
     5144#ifdef  INADDR_BROADCAST
     5145    PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
     5146#else
     5147    PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
     5148#endif
     5149#ifdef  INADDR_LOOPBACK
     5150    PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
     5151#else
     5152    PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
     5153#endif
     5154#ifdef  INADDR_UNSPEC_GROUP
     5155    PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
     5156#else
     5157    PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
     5158#endif
     5159#ifdef  INADDR_ALLHOSTS_GROUP
     5160    PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
     5161                            INADDR_ALLHOSTS_GROUP);
     5162#else
     5163    PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
     5164#endif
     5165#ifdef  INADDR_MAX_LOCAL_GROUP
     5166    PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
     5167                            INADDR_MAX_LOCAL_GROUP);
     5168#else
     5169    PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
     5170#endif
     5171#ifdef  INADDR_NONE
     5172    PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
     5173#else
     5174    PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
     5175#endif
     5176
     5177    /* IPv4 [gs]etsockopt options */
     5178#ifdef  IP_OPTIONS
     5179    PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
     5180#endif
     5181#ifdef  IP_HDRINCL
     5182    PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
     5183#endif
     5184#ifdef  IP_TOS
     5185    PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
     5186#endif
     5187#ifdef  IP_TTL
     5188    PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
     5189#endif
     5190#ifdef  IP_RECVOPTS
     5191    PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
     5192#endif
     5193#ifdef  IP_RECVRETOPTS
     5194    PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
     5195#endif
     5196#ifdef  IP_RECVDSTADDR
     5197    PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
     5198#endif
     5199#ifdef  IP_RETOPTS
     5200    PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
     5201#endif
     5202#ifdef  IP_MULTICAST_IF
     5203    PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
     5204#endif
     5205#ifdef  IP_MULTICAST_TTL
     5206    PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
     5207#endif
     5208#ifdef  IP_MULTICAST_LOOP
     5209    PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
     5210#endif
     5211#ifdef  IP_ADD_MEMBERSHIP
     5212    PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
     5213#endif
     5214#ifdef  IP_DROP_MEMBERSHIP
     5215    PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
     5216#endif
     5217#ifdef  IP_DEFAULT_MULTICAST_TTL
     5218    PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
     5219                            IP_DEFAULT_MULTICAST_TTL);
     5220#endif
     5221#ifdef  IP_DEFAULT_MULTICAST_LOOP
     5222    PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
     5223                            IP_DEFAULT_MULTICAST_LOOP);
     5224#endif
     5225#ifdef  IP_MAX_MEMBERSHIPS
     5226    PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
     5227#endif
     5228
     5229    /* IPv6 [gs]etsockopt options, defined in RFC2553 */
     5230#ifdef  IPV6_JOIN_GROUP
     5231    PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
     5232#endif
     5233#ifdef  IPV6_LEAVE_GROUP
     5234    PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
     5235#endif
     5236#ifdef  IPV6_MULTICAST_HOPS
     5237    PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
     5238#endif
     5239#ifdef  IPV6_MULTICAST_IF
     5240    PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
     5241#endif
     5242#ifdef  IPV6_MULTICAST_LOOP
     5243    PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
     5244#endif
     5245#ifdef  IPV6_UNICAST_HOPS
     5246    PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
     5247#endif
     5248    /* Additional IPV6 socket options, defined in RFC 3493 */
    50285249#ifdef IPV6_V6ONLY
    5029         PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
    5030 #endif
    5031         /* Advanced IPV6 socket options, from RFC 3542 */
     5250    PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
     5251#endif
     5252    /* Advanced IPV6 socket options, from RFC 3542 */
    50325253#ifdef IPV6_CHECKSUM
    5033         PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
     5254    PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
    50345255#endif
    50355256#ifdef IPV6_DONTFRAG
    5036         PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
     5257    PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
    50375258#endif
    50385259#ifdef IPV6_DSTOPTS
    5039         PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
     5260    PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
    50405261#endif
    50415262#ifdef IPV6_HOPLIMIT
    5042         PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
     5263    PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
    50435264#endif
    50445265#ifdef IPV6_HOPOPTS
    5045         PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
     5266    PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
    50465267#endif
    50475268#ifdef IPV6_NEXTHOP
    5048         PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
     5269    PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
    50495270#endif
    50505271#ifdef IPV6_PATHMTU
    5051         PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
     5272    PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
    50525273#endif
    50535274#ifdef IPV6_PKTINFO
    5054         PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
     5275    PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
    50555276#endif
    50565277#ifdef IPV6_RECVDSTOPTS
    5057         PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
     5278    PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
    50585279#endif
    50595280#ifdef IPV6_RECVHOPLIMIT
    5060         PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
     5281    PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
    50615282#endif
    50625283#ifdef IPV6_RECVHOPOPTS
    5063         PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
     5284    PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
    50645285#endif
    50655286#ifdef IPV6_RECVPKTINFO
    5066         PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
     5287    PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
    50675288#endif
    50685289#ifdef IPV6_RECVRTHDR
    5069         PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
     5290    PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
    50705291#endif
    50715292#ifdef IPV6_RECVTCLASS
    5072         PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
     5293    PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
    50735294#endif
    50745295#ifdef IPV6_RTHDR
    5075         PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
     5296    PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
    50765297#endif
    50775298#ifdef IPV6_RTHDRDSTOPTS
    5078         PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
     5299    PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
    50795300#endif
    50805301#ifdef IPV6_RTHDR_TYPE_0
    5081         PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
     5302    PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
    50825303#endif
    50835304#ifdef IPV6_RECVPATHMTU
    5084         PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
     5305    PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
    50855306#endif
    50865307#ifdef IPV6_TCLASS
    5087         PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
     5308    PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
    50885309#endif
    50895310#ifdef IPV6_USE_MIN_MTU
    5090         PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
    5091 #endif
    5092 
    5093         /* TCP options */
    5094 #ifdef  TCP_NODELAY
    5095         PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
    5096 #endif
    5097 #ifdef  TCP_MAXSEG
    5098         PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
    5099 #endif
    5100 #ifdef  TCP_CORK
    5101         PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
    5102 #endif
    5103 #ifdef  TCP_KEEPIDLE
    5104         PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
    5105 #endif
    5106 #ifdef  TCP_KEEPINTVL
    5107         PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
    5108 #endif
    5109 #ifdef  TCP_KEEPCNT
    5110         PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
    5111 #endif
    5112 #ifdef  TCP_SYNCNT
    5113         PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
    5114 #endif
    5115 #ifdef  TCP_LINGER2
    5116         PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
    5117 #endif
    5118 #ifdef  TCP_DEFER_ACCEPT
    5119         PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
    5120 #endif
    5121 #ifdef  TCP_WINDOW_CLAMP
    5122         PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
    5123 #endif
    5124 #ifdef  TCP_INFO
    5125         PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
    5126 #endif
    5127 #ifdef  TCP_QUICKACK
    5128         PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
    5129 #endif
    5130 
    5131 
    5132         /* IPX options */
    5133 #ifdef  IPX_TYPE
    5134         PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
    5135 #endif
    5136 
    5137         /* get{addr,name}info parameters */
     5311    PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
     5312#endif
     5313
     5314    /* TCP options */
     5315#ifdef  TCP_NODELAY
     5316    PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
     5317#endif
     5318#ifdef  TCP_MAXSEG
     5319    PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
     5320#endif
     5321#ifdef  TCP_CORK
     5322    PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
     5323#endif
     5324#ifdef  TCP_KEEPIDLE
     5325    PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
     5326#endif
     5327#ifdef  TCP_KEEPINTVL
     5328    PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
     5329#endif
     5330#ifdef  TCP_KEEPCNT
     5331    PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
     5332#endif
     5333#ifdef  TCP_SYNCNT
     5334    PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
     5335#endif
     5336#ifdef  TCP_LINGER2
     5337    PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
     5338#endif
     5339#ifdef  TCP_DEFER_ACCEPT
     5340    PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
     5341#endif
     5342#ifdef  TCP_WINDOW_CLAMP
     5343    PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
     5344#endif
     5345#ifdef  TCP_INFO
     5346    PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
     5347#endif
     5348#ifdef  TCP_QUICKACK
     5349    PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
     5350#endif
     5351
     5352
     5353    /* IPX options */
     5354#ifdef  IPX_TYPE
     5355    PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
     5356#endif
     5357
     5358    /* get{addr,name}info parameters */
    51385359#ifdef EAI_ADDRFAMILY
    5139         PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
     5360    PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
    51405361#endif
    51415362#ifdef EAI_AGAIN
    5142         PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
     5363    PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
    51435364#endif
    51445365#ifdef EAI_BADFLAGS
    5145         PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
     5366    PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
    51465367#endif
    51475368#ifdef EAI_FAIL
    5148         PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
     5369    PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
    51495370#endif
    51505371#ifdef EAI_FAMILY
    5151         PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
     5372    PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
    51525373#endif
    51535374#ifdef EAI_MEMORY
    5154         PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
     5375    PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
    51555376#endif
    51565377#ifdef EAI_NODATA
    5157         PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
     5378    PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
    51585379#endif
    51595380#ifdef EAI_NONAME
    5160         PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
     5381    PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
    51615382#endif
    51625383#ifdef EAI_OVERFLOW
    5163         PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
     5384    PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
    51645385#endif
    51655386#ifdef EAI_SERVICE
    5166         PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
     5387    PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
    51675388#endif
    51685389#ifdef EAI_SOCKTYPE
    5169         PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
     5390    PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
    51705391#endif
    51715392#ifdef EAI_SYSTEM
    5172         PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
     5393    PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
    51735394#endif
    51745395#ifdef EAI_BADHINTS
    5175         PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
     5396    PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
    51765397#endif
    51775398#ifdef EAI_PROTOCOL
    5178         PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
     5399    PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
    51795400#endif
    51805401#ifdef EAI_MAX
    5181         PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
     5402    PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
    51825403#endif
    51835404#ifdef AI_PASSIVE
    5184         PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
     5405    PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
    51855406#endif
    51865407#ifdef AI_CANONNAME
    5187         PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
     5408    PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
    51885409#endif
    51895410#ifdef AI_NUMERICHOST
    5190         PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
     5411    PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
    51915412#endif
    51925413#ifdef AI_NUMERICSERV
    5193         PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
     5414    PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
    51945415#endif
    51955416#ifdef AI_MASK
    5196         PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
     5417    PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
    51975418#endif
    51985419#ifdef AI_ALL
    5199         PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
     5420    PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
    52005421#endif
    52015422#ifdef AI_V4MAPPED_CFG
    5202         PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
     5423    PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
    52035424#endif
    52045425#ifdef AI_ADDRCONFIG
    5205         PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
     5426    PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
    52065427#endif
    52075428#ifdef AI_V4MAPPED
    5208         PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
     5429    PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
    52095430#endif
    52105431#ifdef AI_DEFAULT
    5211         PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
     5432    PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
    52125433#endif
    52135434#ifdef NI_MAXHOST
    5214         PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
     5435    PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
    52155436#endif
    52165437#ifdef NI_MAXSERV
    5217         PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
     5438    PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
    52185439#endif
    52195440#ifdef NI_NOFQDN
    5220         PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
     5441    PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
    52215442#endif
    52225443#ifdef NI_NUMERICHOST
    5223         PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
     5444    PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
    52245445#endif
    52255446#ifdef NI_NAMEREQD
    5226         PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
     5447    PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
    52275448#endif
    52285449#ifdef NI_NUMERICSERV
    5229         PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
     5450    PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
    52305451#endif
    52315452#ifdef NI_DGRAM
    5232         PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
    5233 #endif
    5234 
    5235         /* shutdown() parameters */
     5453    PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
     5454#endif
     5455
     5456    /* shutdown() parameters */
    52365457#ifdef SHUT_RD
    5237         PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
     5458    PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
    52385459#elif defined(SD_RECEIVE)
    5239         PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
    5240 #else
    5241         PyModule_AddIntConstant(m, "SHUT_RD", 0);
     5460    PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
     5461#else
     5462    PyModule_AddIntConstant(m, "SHUT_RD", 0);
    52425463#endif
    52435464#ifdef SHUT_WR
    5244         PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
     5465    PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
    52455466#elif defined(SD_SEND)
    5246         PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
    5247 #else
    5248         PyModule_AddIntConstant(m, "SHUT_WR", 1);
     5467    PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
     5468#else
     5469    PyModule_AddIntConstant(m, "SHUT_WR", 1);
    52495470#endif
    52505471#ifdef SHUT_RDWR
    5251         PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
     5472    PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
    52525473#elif defined(SD_BOTH)
    5253         PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
    5254 #else
    5255         PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
     5474    PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
     5475#else
     5476    PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
    52565477#endif
    52575478
    52585479#ifdef SIO_RCVALL
    5259         {
    5260                 PyObject *tmp;
    5261                 tmp = PyLong_FromUnsignedLong(SIO_RCVALL);
    5262                 if (tmp == NULL)
    5263                         return;
    5264                 PyModule_AddObject(m, "SIO_RCVALL", tmp);
    5265         }
    5266         PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
    5267         PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
    5268         PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
     5480    {
     5481        DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS};
     5482        const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
     5483        int i;
     5484        for(i = 0; i<sizeof(codes)/sizeof(*codes); ++i) {
     5485            PyObject *tmp;
     5486            tmp = PyLong_FromUnsignedLong(codes[i]);
     5487            if (tmp == NULL)
     5488                return;
     5489            PyModule_AddObject(m, names[i], tmp);
     5490        }
     5491    }
     5492    PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
     5493    PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
     5494    PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
    52695495#ifdef RCVALL_IPLEVEL
    5270         PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
     5496    PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
    52715497#endif
    52725498#ifdef RCVALL_MAX
    5273         PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
     5499    PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
    52745500#endif
    52755501#endif /* _MSTCPIP_ */
    52765502
    5277         /* Initialize gethostbyname lock */
     5503    /* Initialize gethostbyname lock */
    52785504#if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
    5279         netdb_lock = PyThread_allocate_lock();
     5505    netdb_lock = PyThread_allocate_lock();
    52805506#endif
    52815507}
     
    52915517inet_pton(int af, const char *src, void *dst)
    52925518{
    5293         if (af == AF_INET) {
     5519    if (af == AF_INET) {
    52945520#if (SIZEOF_INT != 4)
    52955521#error "Not sure if in_addr_t exists and int is not 32-bits."
    52965522#endif
    5297                 unsigned int packed_addr;
    5298                 packed_addr = inet_addr(src);
    5299                 if (packed_addr == INADDR_NONE)
    5300                         return 0;
    5301                 memcpy(dst, &packed_addr, 4);
    5302                 return 1;
    5303         }
    5304         /* Should set errno to EAFNOSUPPORT */
    5305         return -1;
     5523        unsigned int packed_addr;
     5524        packed_addr = inet_addr(src);
     5525        if (packed_addr == INADDR_NONE)
     5526            return 0;
     5527        memcpy(dst, &packed_addr, 4);
     5528        return 1;
     5529    }
     5530    /* Should set errno to EAFNOSUPPORT */
     5531    return -1;
    53065532}
    53075533
     
    53095535inet_ntop(int af, const void *src, char *dst, socklen_t size)
    53105536{
    5311         if (af == AF_INET) {
    5312                 struct in_addr packed_addr;
    5313                 if (size < 16)
    5314                         /* Should set errno to ENOSPC. */
    5315                         return NULL;
    5316                 memcpy(&packed_addr, src, sizeof(packed_addr));
    5317                 return strncpy(dst, inet_ntoa(packed_addr), size);
    5318         }
    5319         /* Should set errno to EAFNOSUPPORT */
    5320         return NULL;
    5321 }
    5322 
    5323 #endif
    5324 #endif
     5537    if (af == AF_INET) {
     5538        struct in_addr packed_addr;
     5539        if (size < 16)
     5540            /* Should set errno to ENOSPC. */
     5541            return NULL;
     5542        memcpy(&packed_addr, src, sizeof(packed_addr));
     5543        return strncpy(dst, inet_ntoa(packed_addr), size);
     5544    }
     5545    /* Should set errno to EAFNOSUPPORT */
     5546    return NULL;
     5547}
     5548
     5549#endif
     5550#endif
Note: See TracChangeset for help on using the changeset viewer.