Skip to content

gh-107545: Fix misleading setsockopt error message #107546

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Lib/test/test_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -1744,6 +1744,30 @@ def test_getaddrinfo_int_port_overflow(self):
socket.getaddrinfo(None, 0, type=socket.SOCK_STREAM) # No error expected.
socket.getaddrinfo(None, 0xffff, type=socket.SOCK_STREAM) # No error expected.

def test_setsockopt_errors(self):
# See issue #107546.
from _testcapi import INT_MAX, INT_MIN

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.addCleanup(sock.close)

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # No error expected.

with self.assertRaises(OverflowError):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, INT_MAX + 1)

with self.assertRaises(OverflowError):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, INT_MIN - 1)

with self.assertRaises(OverflowError):
sock.setsockopt(socket.SOL_SOCKET, INT_MAX + 1, 1)

with self.assertRaises(OverflowError):
sock.setsockopt(INT_MAX + 1, socket.SO_REUSEADDR, 1)

with self.assertRaises(TypeError):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, dict())

def test_getnameinfo(self):
# only IP addresses are allowed
self.assertRaises(OSError, socket.getnameinfo, ('mail.python.org',0), 0)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve error message when :meth:`setsockopt` raises an error other than a :exc:`TypeError`.
6 changes: 6 additions & 0 deletions Modules/socketmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -3351,6 +3351,9 @@ sock_setsockopt(PyObject *self, PyObject *args)
(char*)&flag, sizeof flag);
goto done;
}
if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
return NULL;
}

PyErr_Clear();
/* setsockopt(level, opt, None, flag) */
Expand All @@ -3361,6 +3364,9 @@ sock_setsockopt(PyObject *self, PyObject *args)
NULL, (socklen_t)optlen);
goto done;
}
if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
return NULL;
}

PyErr_Clear();
/* setsockopt(level, opt, buffer) */
Expand Down
Loading