Skip to content

Commit 8087ccf

Browse files
committed
Add socket.getsockname
1 parent dc0bd73 commit 8087ccf

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

tests/snippets/stdlib_socket.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import socket
22
from testutils import assertRaises
33

4+
45
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
5-
listener.bind(("127.0.0.1", 8080))
6+
listener.bind(("127.0.0.1", 0))
67
listener.listen(1)
78

89
connector = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
9-
connector.connect(("127.0.0.1", 8080))
10+
connector.connect(("127.0.0.1", listener.getsockname()[1]))
1011
connection = listener.accept()[0]
1112

1213
message_a = b'aaaa'

vm/src/stdlib/socket.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,13 @@ impl Connection {
6262
_ => Err(io::Error::new(io::ErrorKind::Other, "oh no!")),
6363
}
6464
}
65+
66+
fn local_addr(&self) -> io::Result<SocketAddr> {
67+
match self {
68+
Connection::TcpListener(con) => con.local_addr(),
69+
_ => Err(io::Error::new(io::ErrorKind::Other, "oh no!")),
70+
}
71+
}
6572
}
6673

6774
impl Read for Connection {
@@ -293,6 +300,33 @@ fn socket_close(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
293300
}
294301
}
295302

303+
fn socket_getsockname(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
304+
arg_check!(vm, args, required = [(zelf, None)]);
305+
match zelf.payload {
306+
PyObjectPayload::Socket { ref socket } => {
307+
let addr = match socket.borrow_mut().con {
308+
Some(ref mut v) => v.local_addr(),
309+
None => return Err(vm.new_type_error("".to_string())),
310+
};
311+
312+
match addr {
313+
Ok(addr) => {
314+
let port = vm.ctx.new_int(addr.port());
315+
let ip = vm.ctx.new_str(addr.ip().to_string());
316+
let elements = RefCell::new(vec![ip, port]);
317+
318+
Ok(PyObject::new(
319+
PyObjectPayload::Sequence { elements },
320+
vm.ctx.tuple_type(),
321+
))
322+
}
323+
_ => return Err(vm.new_type_error("".to_string())),
324+
}
325+
}
326+
_ => Err(vm.new_type_error("".to_string())),
327+
}
328+
}
329+
296330
pub fn mk_module(ctx: &PyContext) -> PyObjectRef {
297331
let py_mod = ctx.new_module(&"socket".to_string(), ctx.new_scope(None));
298332

@@ -318,6 +352,7 @@ pub fn mk_module(ctx: &PyContext) -> PyObjectRef {
318352
ctx.set_attr(&socket, "accept", ctx.new_rustfunc(socket_accept));
319353
ctx.set_attr(&socket, "listen", ctx.new_rustfunc(socket_listen));
320354
ctx.set_attr(&socket, "close", ctx.new_rustfunc(socket_close));
355+
ctx.set_attr(&socket, "getsockname", ctx.new_rustfunc(socket_getsockname));
321356
socket
322357
};
323358
ctx.set_attr(&py_mod, "socket", socket.clone());

0 commit comments

Comments
 (0)