We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
listen(0) in create_server() does not allow client to connect to linux server
## Environment data

- PTVSD version: 4.1.1
- OS and version: linux kernel 4.14.46
- Python version (& distribution if applicable, e.g. Anaconda): 2.7.13, 3.5.3
- Using VS Code or Visual Studio: N/A

## Actual behavior
server on linux never accepts connection, i.e. `client, _ = sock.accept()` in `connect()` in socket.py never returns.  This is due to the `listen(0)` call in `create_server()`.  This was changed from `listen(1)` in 322f6946.  Although `listen(0)` does work correctly on mac, it does not on linux.

## Expected  behavior
the incoming connection to be accepted

## Steps to reproduce:
run:
```python
ptvsd.enable_attach(address=('0.0.0.0', 9876), redirect_output=True)
ptvsd.wait_for_attach()
```
then from the command line, see that `telnet localhost 9876` hangs instead of connecting.  some background history is at https://bugs.python.org/issue8498




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

{"golden_diff": "diff --git a/ptvsd/socket.py b/ptvsd/socket.py\n--- a/ptvsd/socket.py\n+++ b/ptvsd/socket.py\n@@ -75,7 +75,7 @@\n         host = 'localhost'\n     server = _new_sock()\n     server.bind((host, port))\n-    server.listen(0)\n+    server.listen(1)\n     return server\n", "issue": "listen(0) in create_server() does not allow client to connect to linux server\n## Environment data\r\n\r\n- PTVSD version: 4.1.1\r\n- OS and version: linux kernel 4.14.46\r\n- Python version (& distribution if applicable, e.g. Anaconda): 2.7.13, 3.5.3\r\n- Using VS Code or Visual Studio: N/A\r\n\r\n## Actual behavior\r\nserver on linux never accepts connection, i.e. `client, _ = sock.accept()` in `connect()` in socket.py never returns.  This is due to the `listen(0)` call in `create_server()`.  This was changed from `listen(1)` in 322f6946.  Although `listen(0)` does work correctly on mac, it does not on linux.\r\n\r\n## Expected  behavior\r\nthe incoming connection to be accepted\r\n\r\n## Steps to reproduce:\r\nrun:\r\n```python\r\nptvsd.enable_attach(address=('0.0.0.0', 9876), redirect_output=True)\r\nptvsd.wait_for_attach()\r\n```\r\nthen from the command line, see that `telnet localhost 9876` hangs instead of connecting.  some background history is at https://bugs.python.org/issue8498\r\n\r\n\r\n\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 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):\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    server.listen(0)\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    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 positive 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 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):\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    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    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 positive 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"}]}