We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Use SIO_LOOPBACK_FAST_PATH
Python 3.6 adds the SIO_LOOPBACK_FAST_PATH flag for sockets, which dramatically increases the bandwidth for loopback connections (I got >4x on my machine with the test code on the linked issue).

We should enable this flag where possible in our debugger. The functionality has existed since Windows 8, but using it on earlier OSs may cause an exception. It is safe to use if the socket eventually gets a connection from another IP.

Moved from https://github.com/Microsoft/PTVS/issues/1350

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `ptvsd/socket.py`
Content:
```
1 # Copyright (c) Microsoft Corporation. All rights reserved.
2 # Licensed under the MIT License. See LICENSE in the project root
3 # for license information.
4 
5 from __future__ import absolute_import
6 
7 from collections import namedtuple
8 import contextlib
9 import errno
10 import platform
11 import socket
12 try:
13     from urllib.parse import urlparse
14 except ImportError:
15     from urlparse import urlparse
16 
17 
18 try:
19     ConnectionError  # noqa
20     BrokenPipeError  # noqa
21     ConnectionResetError  # noqa
22 except NameError:
23     class BrokenPipeError(Exception):
24         # EPIPE and ESHUTDOWN
25         pass
26 
27     class ConnectionResetError(Exception):
28         # ECONNRESET
29         pass
30 
31 
32 NOT_CONNECTED = (
33     errno.ENOTCONN,
34     errno.EBADF,
35 )
36 
37 CLOSED = (
38     errno.EPIPE,
39     errno.ESHUTDOWN,
40     errno.ECONNRESET,
41     # Windows
42     10038,  # "An operation was attempted on something that is not a socket"
43     10058,
44 )
45 
46 EOF = NOT_CONNECTED + CLOSED
47 
48 
49 @contextlib.contextmanager
50 def convert_eof():
51     """A context manager to convert some socket errors into EOFError."""
52     try:
53         yield
54     except ConnectionResetError:
55         raise EOFError
56     except BrokenPipeError:
57         raise EOFError
58     except OSError as exc:
59         if exc.errno in EOF:
60             raise EOFError
61         raise
62 
63 
64 class TimeoutError(socket.timeout):
65     """A socket timeout happened."""
66 
67 
68 def is_socket(sock):
69     """Return True if the object can be used as a socket."""
70     return isinstance(sock, socket.socket)
71 
72 
73 def create_server(host, port, timeout=None):
74     """Return a local server socket listening on the given port."""
75     if host is None:
76         host = 'localhost'
77     server = _new_sock()
78     server.bind((host, port))
79 
80     # _, listener_port = server.getsockname()
81     # print('Listening on', listener_port)
82 
83     if timeout is not None:
84         server.settimeout(timeout)
85     server.listen(1)
86     return server
87 
88 
89 def create_client():
90     """Return a client socket that may be connected to a remote address."""
91     return _new_sock()
92 
93 
94 def _new_sock():
95     sock = socket.socket(socket.AF_INET,
96                          socket.SOCK_STREAM,
97                          socket.IPPROTO_TCP)
98     if platform.system() == 'Windows':
99         sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
100     else:
101         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
102     return sock
103 
104 
105 @contextlib.contextmanager
106 def ignored_errno(*ignored):
107     """A context manager that ignores the given errnos."""
108     try:
109         yield
110     except OSError as exc:
111         if exc.errno not in ignored:
112             raise
113 
114 
115 class KeepAlive(namedtuple('KeepAlive', 'interval idle maxfails')):
116     """TCP keep-alive settings."""
117 
118     INTERVAL = 3  # seconds
119     IDLE = 1  # seconds after idle
120     MAX_FAILS = 5
121 
122     @classmethod
123     def from_raw(cls, raw):
124         """Return the corresponding KeepAlive."""
125         if raw is None:
126             return None
127         elif isinstance(raw, cls):
128             return raw
129         elif isinstance(raw, (str, int, float)):
130             return cls(raw)
131         else:
132             try:
133                 raw = dict(raw)
134             except TypeError:
135                 return cls(*raw)
136             else:
137                 return cls(**raw)
138 
139     def __new__(cls, interval=None, idle=None, maxfails=None):
140         self = super(KeepAlive, cls).__new__(
141             cls,
142             float(interval) if interval or interval == 0 else cls.INTERVAL,
143             float(idle) if idle or idle == 0 else cls.IDLE,
144             float(maxfails) if maxfails or maxfails == 0 else cls.MAX_FAILS,
145         )
146         return self
147 
148     def apply(self, sock):
149         """Set the keepalive values on the socket."""
150         sock.setsockopt(socket.SOL_SOCKET,
151                         socket.SO_KEEPALIVE,
152                         1)
153         interval = self.interval
154         idle = self.idle
155         maxfails = self.maxfails
156         try:
157             if interval > 0:
158                 sock.setsockopt(socket.IPPROTO_TCP,
159                                 socket.TCP_KEEPINTVL,
160                                 interval)
161             if idle > 0:
162                 sock.setsockopt(socket.IPPROTO_TCP,
163                                 socket.TCP_KEEPIDLE,
164                                 idle)
165             if maxfails >= 0:
166                 sock.setsockopt(socket.IPPROTO_TCP,
167                                 socket.TCP_KEEPCNT,
168                                 maxfails)
169         except AttributeError:
170             # mostly linux-only
171             pass
172 
173 
174 def connect(sock, addr, keepalive=None):
175     """Return the client socket for the next connection."""
176     if addr is None:
177         if keepalive is None or keepalive is True:
178             keepalive = KeepAlive()
179         elif keepalive:
180             keepalive = KeepAlive.from_raw(keepalive)
181         client, _ = sock.accept()
182         if keepalive:
183             keepalive.apply(client)
184         return client
185     else:
186         if keepalive:
187             raise NotImplementedError
188         sock.connect(addr)
189         return sock
190 
191 
192 def shut_down(sock, how=socket.SHUT_RDWR, ignored=NOT_CONNECTED):
193     """Shut down the given socket."""
194     with ignored_errno(*ignored or ()):
195         sock.shutdown(how)
196 
197 
198 def close_socket(sock):
199     """Shutdown and close the socket."""
200     try:
201         shut_down(sock)
202     except Exception:
203         # TODO: Log errors?
204         pass
205     sock.close()
206 
207 
208 class Address(namedtuple('Address', 'host port')):
209     """An IP address to use for sockets."""
210 
211     @classmethod
212     def from_raw(cls, raw, defaultport=None):
213         """Return an address corresponding to the given data."""
214         if isinstance(raw, cls):
215             return raw
216         elif isinstance(raw, int):
217             return cls(None, raw)
218         elif isinstance(raw, str):
219             if raw == '':
220                 return cls('', defaultport)
221             parsed = urlparse(raw)
222             if not parsed.netloc:
223                 if parsed.scheme:
224                     raise ValueError('invalid address {!r}'.format(raw))
225                 return cls.from_raw('x://' + raw, defaultport=defaultport)
226             return cls(
227                 parsed.hostname or '',
228                 parsed.port if parsed.port else defaultport,
229             )
230         elif not raw:
231             return cls(None, defaultport)
232         else:
233             try:
234                 kwargs = dict(**raw)
235             except TypeError:
236                 return cls(*raw)
237             else:
238                 kwargs.setdefault('host', None)
239                 kwargs.setdefault('port', defaultport)
240                 return cls(**kwargs)
241 
242     @classmethod
243     def as_server(cls, host, port):
244         """Return an address to use as a server address."""
245         return cls(host, port, isserver=True)
246 
247     @classmethod
248     def as_client(cls, host, port):
249         """Return an address to use as a server address."""
250         return cls(host, port, isserver=False)
251 
252     def __new__(cls, host, port, **kwargs):
253         if host == '*':
254             host = ''
255         isserver = kwargs.pop('isserver', None)
256         if isserver is None:
257             isserver = (host is None or host == '')
258         else:
259             isserver = bool(isserver)
260         if host is None:
261             host = 'localhost'
262         self = super(Address, cls).__new__(
263             cls,
264             str(host),
265             int(port) if port is not None else None,
266             **kwargs
267         )
268         self._isserver = isserver
269         return self
270 
271     def __init__(self, *args, **kwargs):
272         if self.port is None:
273             raise TypeError('missing port')
274         if self.port < 0 or self.port > 65535:
275             raise ValueError('port must be non-negative int < 65535')
276 
277     def __repr__(self):
278         orig = super(Address, self).__repr__()
279         return '{}, isserver={})'.format(orig[:-1], self._isserver)
280 
281     def __eq__(self, other):
282         if not super(Address, self).__eq__(other):
283             return False
284         try:
285             other = self.from_raw(other)
286         except Exception:
287             return False
288         return self._isserver == other._isserver
289 
290     @property
291     def isserver(self):
292         return self._isserver
293
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/ptvsd/socket.py b/ptvsd/socket.py
--- a/ptvsd/socket.py
+++ b/ptvsd/socket.py
@@ -75,14 +75,14 @@
     if host is None:
         host = 'localhost'
     server = _new_sock()
-    server.bind((host, port))
-
-    # _, listener_port = server.getsockname()
-    # print('Listening on', listener_port)
-
-    if timeout is not None:
-        server.settimeout(timeout)
-    server.listen(1)
+    try:
+        server.bind((host, port))
+        if timeout is not None:
+            server.settimeout(timeout)
+        server.listen(1)
+    except Exception:
+        server.close()
+        raise
     return server
 
 
@@ -96,6 +96,15 @@
                          socket.SOCK_STREAM,
                          socket.IPPROTO_TCP)
     if platform.system() == 'Windows':
+        try:
+            sock.ioctl(socket.SIO_LOOPBACK_FAST_PATH, True)
+        except AttributeError:
+            pass  # Not supported in python 2.* or <3.6
+        except OSError as ose:
+            if ose.winerror == 10045:  # Not supported by OS
+                pass
+            else:
+                raise
         sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
     else:
         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
@@ -200,7 +209,6 @@
     try:
         shut_down(sock)
     except Exception:
-        # TODO: Log errors?
         pass
     sock.close()

{"golden_diff": "diff --git a/ptvsd/socket.py b/ptvsd/socket.py\n--- a/ptvsd/socket.py\n+++ b/ptvsd/socket.py\n@@ -75,14 +75,14 @@\n     if host is None:\n         host = 'localhost'\n     server = _new_sock()\n-    server.bind((host, port))\n-\n-    # _, listener_port = server.getsockname()\n-    # print('Listening on', listener_port)\n-\n-    if timeout is not None:\n-        server.settimeout(timeout)\n-    server.listen(1)\n+    try:\n+        server.bind((host, port))\n+        if timeout is not None:\n+            server.settimeout(timeout)\n+        server.listen(1)\n+    except Exception:\n+        server.close()\n+        raise\n     return server\n \n \n@@ -96,6 +96,15 @@\n                          socket.SOCK_STREAM,\n                          socket.IPPROTO_TCP)\n     if platform.system() == 'Windows':\n+        try:\n+            sock.ioctl(socket.SIO_LOOPBACK_FAST_PATH, True)\n+        except AttributeError:\n+            pass  # Not supported in python 2.* or <3.6\n+        except OSError as ose:\n+            if ose.winerror == 10045:  # Not supported by OS\n+                pass\n+            else:\n+                raise\n         sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)\n     else:\n         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n@@ -200,7 +209,6 @@\n     try:\n         shut_down(sock)\n     except Exception:\n-        # TODO: Log errors?\n         pass\n     sock.close()\n", "issue": "Use SIO_LOOPBACK_FAST_PATH\nPython 3.6 adds the SIO_LOOPBACK_FAST_PATH flag for sockets, which dramatically increases the bandwidth for loopback connections (I got >4x on my machine with the test code on the linked issue).\r\n\r\nWe should enable this flag where possible in our debugger. The functionality has existed since Windows 8, but using it on earlier OSs may cause an exception. It is safe to use if the socket eventually gets a connection from another IP.\r\n\r\nMoved from https://github.com/Microsoft/PTVS/issues/1350\n", "before_files": [{"content": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nfrom __future__ import absolute_import\n\nfrom collections import namedtuple\nimport contextlib\nimport errno\nimport platform\nimport socket\ntry:\n    from urllib.parse import urlparse\nexcept ImportError:\n    from urlparse import urlparse\n\n\ntry:\n    ConnectionError  # noqa\n    BrokenPipeError  # noqa\n    ConnectionResetError  # noqa\nexcept NameError:\n    class BrokenPipeError(Exception):\n        # EPIPE and ESHUTDOWN\n        pass\n\n    class ConnectionResetError(Exception):\n        # ECONNRESET\n        pass\n\n\nNOT_CONNECTED = (\n    errno.ENOTCONN,\n    errno.EBADF,\n)\n\nCLOSED = (\n    errno.EPIPE,\n    errno.ESHUTDOWN,\n    errno.ECONNRESET,\n    # Windows\n    10038,  # \"An operation was attempted on something that is not a socket\"\n    10058,\n)\n\nEOF = NOT_CONNECTED + CLOSED\n\n\n@contextlib.contextmanager\ndef convert_eof():\n    \"\"\"A context manager to convert some socket errors into EOFError.\"\"\"\n    try:\n        yield\n    except ConnectionResetError:\n        raise EOFError\n    except BrokenPipeError:\n        raise EOFError\n    except OSError as exc:\n        if exc.errno in EOF:\n            raise EOFError\n        raise\n\n\nclass TimeoutError(socket.timeout):\n    \"\"\"A socket timeout happened.\"\"\"\n\n\ndef is_socket(sock):\n    \"\"\"Return True if the object can be used as a socket.\"\"\"\n    return isinstance(sock, socket.socket)\n\n\ndef create_server(host, port, timeout=None):\n    \"\"\"Return a local server socket listening on the given port.\"\"\"\n    if host is None:\n        host = 'localhost'\n    server = _new_sock()\n    server.bind((host, port))\n\n    # _, listener_port = server.getsockname()\n    # print('Listening on', listener_port)\n\n    if timeout is not None:\n        server.settimeout(timeout)\n    server.listen(1)\n    return server\n\n\ndef create_client():\n    \"\"\"Return a client socket that may be connected to a remote address.\"\"\"\n    return _new_sock()\n\n\ndef _new_sock():\n    sock = socket.socket(socket.AF_INET,\n                         socket.SOCK_STREAM,\n                         socket.IPPROTO_TCP)\n    if platform.system() == 'Windows':\n        sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)\n    else:\n        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n    return sock\n\n\n@contextlib.contextmanager\ndef ignored_errno(*ignored):\n    \"\"\"A context manager that ignores the given errnos.\"\"\"\n    try:\n        yield\n    except OSError as exc:\n        if exc.errno not in ignored:\n            raise\n\n\nclass KeepAlive(namedtuple('KeepAlive', 'interval idle maxfails')):\n    \"\"\"TCP keep-alive settings.\"\"\"\n\n    INTERVAL = 3  # seconds\n    IDLE = 1  # seconds after idle\n    MAX_FAILS = 5\n\n    @classmethod\n    def from_raw(cls, raw):\n        \"\"\"Return the corresponding KeepAlive.\"\"\"\n        if raw is None:\n            return None\n        elif isinstance(raw, cls):\n            return raw\n        elif isinstance(raw, (str, int, float)):\n            return cls(raw)\n        else:\n            try:\n                raw = dict(raw)\n            except TypeError:\n                return cls(*raw)\n            else:\n                return cls(**raw)\n\n    def __new__(cls, interval=None, idle=None, maxfails=None):\n        self = super(KeepAlive, cls).__new__(\n            cls,\n            float(interval) if interval or interval == 0 else cls.INTERVAL,\n            float(idle) if idle or idle == 0 else cls.IDLE,\n            float(maxfails) if maxfails or maxfails == 0 else cls.MAX_FAILS,\n        )\n        return self\n\n    def apply(self, sock):\n        \"\"\"Set the keepalive values on the socket.\"\"\"\n        sock.setsockopt(socket.SOL_SOCKET,\n                        socket.SO_KEEPALIVE,\n                        1)\n        interval = self.interval\n        idle = self.idle\n        maxfails = self.maxfails\n        try:\n            if interval > 0:\n                sock.setsockopt(socket.IPPROTO_TCP,\n                                socket.TCP_KEEPINTVL,\n                                interval)\n            if idle > 0:\n                sock.setsockopt(socket.IPPROTO_TCP,\n                                socket.TCP_KEEPIDLE,\n                                idle)\n            if maxfails >= 0:\n                sock.setsockopt(socket.IPPROTO_TCP,\n                                socket.TCP_KEEPCNT,\n                                maxfails)\n        except AttributeError:\n            # mostly linux-only\n            pass\n\n\ndef connect(sock, addr, keepalive=None):\n    \"\"\"Return the client socket for the next connection.\"\"\"\n    if addr is None:\n        if keepalive is None or keepalive is True:\n            keepalive = KeepAlive()\n        elif keepalive:\n            keepalive = KeepAlive.from_raw(keepalive)\n        client, _ = sock.accept()\n        if keepalive:\n            keepalive.apply(client)\n        return client\n    else:\n        if keepalive:\n            raise NotImplementedError\n        sock.connect(addr)\n        return sock\n\n\ndef shut_down(sock, how=socket.SHUT_RDWR, ignored=NOT_CONNECTED):\n    \"\"\"Shut down the given socket.\"\"\"\n    with ignored_errno(*ignored or ()):\n        sock.shutdown(how)\n\n\ndef close_socket(sock):\n    \"\"\"Shutdown and close the socket.\"\"\"\n    try:\n        shut_down(sock)\n    except Exception:\n        # TODO: Log errors?\n        pass\n    sock.close()\n\n\nclass Address(namedtuple('Address', 'host port')):\n    \"\"\"An IP address to use for sockets.\"\"\"\n\n    @classmethod\n    def from_raw(cls, raw, defaultport=None):\n        \"\"\"Return an address corresponding to the given data.\"\"\"\n        if isinstance(raw, cls):\n            return raw\n        elif isinstance(raw, int):\n            return cls(None, raw)\n        elif isinstance(raw, str):\n            if raw == '':\n                return cls('', defaultport)\n            parsed = urlparse(raw)\n            if not parsed.netloc:\n                if parsed.scheme:\n                    raise ValueError('invalid address {!r}'.format(raw))\n                return cls.from_raw('x://' + raw, defaultport=defaultport)\n            return cls(\n                parsed.hostname or '',\n                parsed.port if parsed.port else defaultport,\n            )\n        elif not raw:\n            return cls(None, defaultport)\n        else:\n            try:\n                kwargs = dict(**raw)\n            except TypeError:\n                return cls(*raw)\n            else:\n                kwargs.setdefault('host', None)\n                kwargs.setdefault('port', defaultport)\n                return cls(**kwargs)\n\n    @classmethod\n    def as_server(cls, host, port):\n        \"\"\"Return an address to use as a server address.\"\"\"\n        return cls(host, port, isserver=True)\n\n    @classmethod\n    def as_client(cls, host, port):\n        \"\"\"Return an address to use as a server address.\"\"\"\n        return cls(host, port, isserver=False)\n\n    def __new__(cls, host, port, **kwargs):\n        if host == '*':\n            host = ''\n        isserver = kwargs.pop('isserver', None)\n        if isserver is None:\n            isserver = (host is None or host == '')\n        else:\n            isserver = bool(isserver)\n        if host is None:\n            host = 'localhost'\n        self = super(Address, cls).__new__(\n            cls,\n            str(host),\n            int(port) if port is not None else None,\n            **kwargs\n        )\n        self._isserver = isserver\n        return self\n\n    def __init__(self, *args, **kwargs):\n        if self.port is None:\n            raise TypeError('missing port')\n        if self.port < 0 or self.port > 65535:\n            raise ValueError('port must be non-negative int < 65535')\n\n    def __repr__(self):\n        orig = super(Address, self).__repr__()\n        return '{}, isserver={})'.format(orig[:-1], self._isserver)\n\n    def __eq__(self, other):\n        if not super(Address, self).__eq__(other):\n            return False\n        try:\n            other = self.from_raw(other)\n        except Exception:\n            return False\n        return self._isserver == other._isserver\n\n    @property\n    def isserver(self):\n        return self._isserver\n", "path": "ptvsd/socket.py"}], "after_files": [{"content": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nfrom __future__ import absolute_import\n\nfrom collections import namedtuple\nimport contextlib\nimport errno\nimport platform\nimport socket\ntry:\n    from urllib.parse import urlparse\nexcept ImportError:\n    from urlparse import urlparse\n\n\ntry:\n    ConnectionError  # noqa\n    BrokenPipeError  # noqa\n    ConnectionResetError  # noqa\nexcept NameError:\n    class BrokenPipeError(Exception):\n        # EPIPE and ESHUTDOWN\n        pass\n\n    class ConnectionResetError(Exception):\n        # ECONNRESET\n        pass\n\n\nNOT_CONNECTED = (\n    errno.ENOTCONN,\n    errno.EBADF,\n)\n\nCLOSED = (\n    errno.EPIPE,\n    errno.ESHUTDOWN,\n    errno.ECONNRESET,\n    # Windows\n    10038,  # \"An operation was attempted on something that is not a socket\"\n    10058,\n)\n\nEOF = NOT_CONNECTED + CLOSED\n\n\n@contextlib.contextmanager\ndef convert_eof():\n    \"\"\"A context manager to convert some socket errors into EOFError.\"\"\"\n    try:\n        yield\n    except ConnectionResetError:\n        raise EOFError\n    except BrokenPipeError:\n        raise EOFError\n    except OSError as exc:\n        if exc.errno in EOF:\n            raise EOFError\n        raise\n\n\nclass TimeoutError(socket.timeout):\n    \"\"\"A socket timeout happened.\"\"\"\n\n\ndef is_socket(sock):\n    \"\"\"Return True if the object can be used as a socket.\"\"\"\n    return isinstance(sock, socket.socket)\n\n\ndef create_server(host, port, timeout=None):\n    \"\"\"Return a local server socket listening on the given port.\"\"\"\n    if host is None:\n        host = 'localhost'\n    server = _new_sock()\n    try:\n        server.bind((host, port))\n        if timeout is not None:\n            server.settimeout(timeout)\n        server.listen(1)\n    except Exception:\n        server.close()\n        raise\n    return server\n\n\ndef create_client():\n    \"\"\"Return a client socket that may be connected to a remote address.\"\"\"\n    return _new_sock()\n\n\ndef _new_sock():\n    sock = socket.socket(socket.AF_INET,\n                         socket.SOCK_STREAM,\n                         socket.IPPROTO_TCP)\n    if platform.system() == 'Windows':\n        try:\n            sock.ioctl(socket.SIO_LOOPBACK_FAST_PATH, True)\n        except AttributeError:\n            pass  # Not supported in python 2.* or <3.6\n        except OSError as ose:\n            if ose.winerror == 10045:  # Not supported by OS\n                pass\n            else:\n                raise\n        sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)\n    else:\n        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n    return sock\n\n\n@contextlib.contextmanager\ndef ignored_errno(*ignored):\n    \"\"\"A context manager that ignores the given errnos.\"\"\"\n    try:\n        yield\n    except OSError as exc:\n        if exc.errno not in ignored:\n            raise\n\n\nclass KeepAlive(namedtuple('KeepAlive', 'interval idle maxfails')):\n    \"\"\"TCP keep-alive settings.\"\"\"\n\n    INTERVAL = 3  # seconds\n    IDLE = 1  # seconds after idle\n    MAX_FAILS = 5\n\n    @classmethod\n    def from_raw(cls, raw):\n        \"\"\"Return the corresponding KeepAlive.\"\"\"\n        if raw is None:\n            return None\n        elif isinstance(raw, cls):\n            return raw\n        elif isinstance(raw, (str, int, float)):\n            return cls(raw)\n        else:\n            try:\n                raw = dict(raw)\n            except TypeError:\n                return cls(*raw)\n            else:\n                return cls(**raw)\n\n    def __new__(cls, interval=None, idle=None, maxfails=None):\n        self = super(KeepAlive, cls).__new__(\n            cls,\n            float(interval) if interval or interval == 0 else cls.INTERVAL,\n            float(idle) if idle or idle == 0 else cls.IDLE,\n            float(maxfails) if maxfails or maxfails == 0 else cls.MAX_FAILS,\n        )\n        return self\n\n    def apply(self, sock):\n        \"\"\"Set the keepalive values on the socket.\"\"\"\n        sock.setsockopt(socket.SOL_SOCKET,\n                        socket.SO_KEEPALIVE,\n                        1)\n        interval = self.interval\n        idle = self.idle\n        maxfails = self.maxfails\n        try:\n            if interval > 0:\n                sock.setsockopt(socket.IPPROTO_TCP,\n                                socket.TCP_KEEPINTVL,\n                                interval)\n            if idle > 0:\n                sock.setsockopt(socket.IPPROTO_TCP,\n                                socket.TCP_KEEPIDLE,\n                                idle)\n            if maxfails >= 0:\n                sock.setsockopt(socket.IPPROTO_TCP,\n                                socket.TCP_KEEPCNT,\n                                maxfails)\n        except AttributeError:\n            # mostly linux-only\n            pass\n\n\ndef connect(sock, addr, keepalive=None):\n    \"\"\"Return the client socket for the next connection.\"\"\"\n    if addr is None:\n        if keepalive is None or keepalive is True:\n            keepalive = KeepAlive()\n        elif keepalive:\n            keepalive = KeepAlive.from_raw(keepalive)\n        client, _ = sock.accept()\n        if keepalive:\n            keepalive.apply(client)\n        return client\n    else:\n        if keepalive:\n            raise NotImplementedError\n        sock.connect(addr)\n        return sock\n\n\ndef shut_down(sock, how=socket.SHUT_RDWR, ignored=NOT_CONNECTED):\n    \"\"\"Shut down the given socket.\"\"\"\n    with ignored_errno(*ignored or ()):\n        sock.shutdown(how)\n\n\ndef close_socket(sock):\n    \"\"\"Shutdown and close the socket.\"\"\"\n    try:\n        shut_down(sock)\n    except Exception:\n        pass\n    sock.close()\n\n\nclass Address(namedtuple('Address', 'host port')):\n    \"\"\"An IP address to use for sockets.\"\"\"\n\n    @classmethod\n    def from_raw(cls, raw, defaultport=None):\n        \"\"\"Return an address corresponding to the given data.\"\"\"\n        if isinstance(raw, cls):\n            return raw\n        elif isinstance(raw, int):\n            return cls(None, raw)\n        elif isinstance(raw, str):\n            if raw == '':\n                return cls('', defaultport)\n            parsed = urlparse(raw)\n            if not parsed.netloc:\n                if parsed.scheme:\n                    raise ValueError('invalid address {!r}'.format(raw))\n                return cls.from_raw('x://' + raw, defaultport=defaultport)\n            return cls(\n                parsed.hostname or '',\n                parsed.port if parsed.port else defaultport,\n            )\n        elif not raw:\n            return cls(None, defaultport)\n        else:\n            try:\n                kwargs = dict(**raw)\n            except TypeError:\n                return cls(*raw)\n            else:\n                kwargs.setdefault('host', None)\n                kwargs.setdefault('port', defaultport)\n                return cls(**kwargs)\n\n    @classmethod\n    def as_server(cls, host, port):\n        \"\"\"Return an address to use as a server address.\"\"\"\n        return cls(host, port, isserver=True)\n\n    @classmethod\n    def as_client(cls, host, port):\n        \"\"\"Return an address to use as a server address.\"\"\"\n        return cls(host, port, isserver=False)\n\n    def __new__(cls, host, port, **kwargs):\n        if host == '*':\n            host = ''\n        isserver = kwargs.pop('isserver', None)\n        if isserver is None:\n            isserver = (host is None or host == '')\n        else:\n            isserver = bool(isserver)\n        if host is None:\n            host = 'localhost'\n        self = super(Address, cls).__new__(\n            cls,\n            str(host),\n            int(port) if port is not None else None,\n            **kwargs\n        )\n        self._isserver = isserver\n        return self\n\n    def __init__(self, *args, **kwargs):\n        if self.port is None:\n            raise TypeError('missing port')\n        if self.port < 0 or self.port > 65535:\n            raise ValueError('port must be non-negative int < 65535')\n\n    def __repr__(self):\n        orig = super(Address, self).__repr__()\n        return '{}, isserver={})'.format(orig[:-1], self._isserver)\n\n    def __eq__(self, other):\n        if not super(Address, self).__eq__(other):\n            return False\n        try:\n            other = self.from_raw(other)\n        except Exception:\n            return False\n        return self._isserver == other._isserver\n\n    @property\n    def isserver(self):\n        return self._isserver\n", "path": "ptvsd/socket.py"}]}