[Python-checkins] cpython: socket_gethostname() uses a wchar_t* with PyMem_Malloc() to avoid the
victor.stinner
python-checkins at python.org
Thu Nov 17 01:09:38 CET 2011
http://hg.python.org/cpython/rev/488a2e41e89d
changeset: 73594:488a2e41e89d
user: Victor Stinner <victor.stinner at haypocalc.com>
date: Thu Nov 17 01:11:36 2011 +0100
summary:
socket_gethostname() uses a wchar_t* with PyMem_Malloc() to avoid the
old Unicode API.
files:
Modules/socketmodule.c | 44 ++++++++++++++++++-----------
1 files changed, 27 insertions(+), 17 deletions(-)
diff --git a/Modules/socketmodule.c b/Modules/socketmodule.c
--- a/Modules/socketmodule.c
+++ b/Modules/socketmodule.c
@@ -3896,24 +3896,34 @@
Otherwise, gethostname apparently also returns the DNS name. */
wchar_t buf[MAX_COMPUTERNAME_LENGTH + 1];
DWORD size = Py_ARRAY_LENGTH(buf);
+ wchar_t *name;
PyObject *result;
- if (!GetComputerNameExW(ComputerNamePhysicalDnsHostname, buf, &size)) {
- if (GetLastError() == ERROR_MORE_DATA) {
- /* MSDN says this may occur "because DNS allows longer names */
- if (size == 0) /* XXX: I'm not sure how to handle this */
- return PyUnicode_FromUnicode(NULL, 0);
- result = PyUnicode_FromUnicode(NULL, size - 1);
- if (!result)
- return NULL;
- if (GetComputerNameExW(ComputerNamePhysicalDnsHostname,
- PyUnicode_AS_UNICODE(result),
- &size))
- return result;
- Py_DECREF(result);
- }
- return PyErr_SetExcFromWindowsErr(PyExc_WindowsError, GetLastError());
- }
- return PyUnicode_FromUnicode(buf, size);
+
+ if (GetComputerNameExW(ComputerNamePhysicalDnsHostname, buf, &size))
+ return PyUnicode_FromUnicode(buf, size);
+
+ if (GetLastError() != ERROR_MORE_DATA)
+ return PyErr_SetFromWindowsErr(0);
+
+ if (size == 0)
+ return PyUnicode_New(0, 0);
+
+ /* MSDN says ERROR_MORE_DATA may occur because DNS allows longer
+ names */
+ name = PyMem_Malloc(size * sizeof(wchar_t));
+ if (!name)
+ return NULL;
+ if (!GetComputerNameExW(ComputerNamePhysicalDnsHostname,
+ name,
+ &size))
+ {
+ PyMem_Free(name);
+ return PyErr_SetFromWindowsErr(0);
+ }
+
+ result = PyUnicode_FromWideChar(name, size);
+ PyMem_Free(name);
+ return result;
#else
char buf[1024];
int res;
--
Repository URL: http://hg.python.org/cpython
More information about the Python-checkins
mailing list