MCPcopy Index your code
hub / github.com/RustPython/RustPython / getaddrinfo

Function getaddrinfo

crates/stdlib/src/socket.rs:2842–2917  ·  view source on GitHub ↗
(
        opts: GAIOptions,
        vm: &VirtualMachine,
    )

Source from the content-addressed store, hash-verified

2840
2841 #[pyfunction]
2842 fn getaddrinfo(
2843 opts: GAIOptions,
2844 vm: &VirtualMachine,
2845 ) -> Result<Vec<PyObjectRef>, IoOrPyException> {
2846 let hints = dns_lookup::AddrInfoHints {
2847 socktype: opts.ty,
2848 protocol: opts.proto,
2849 address: opts.family,
2850 flags: opts.flags,
2851 };
2852
2853 // Encode host: str uses IDNA encoding, bytes must be valid UTF-8
2854 let host_encoded: Option<String> = match opts.host.as_ref() {
2855 Some(ArgStrOrBytesLike::Str(s)) => {
2856 let encoded =
2857 vm.state
2858 .codec_registry
2859 .encode_text(s.to_owned(), "idna", None, vm)?;
2860 let host_str = core::str::from_utf8(encoded.as_bytes())
2861 .map_err(|_| vm.new_runtime_error("idna output is not utf8"))?;
2862 Some(host_str.to_owned())
2863 }
2864 Some(ArgStrOrBytesLike::Buf(b)) => {
2865 let bytes = b.borrow_buf();
2866 let host_str = core::str::from_utf8(&bytes)
2867 .map_err(|_| vm.new_unicode_decode_error("host bytes is not utf8"))?;
2868 Some(host_str.to_owned())
2869 }
2870 None => None,
2871 };
2872 let host = host_encoded.as_deref();
2873
2874 // Encode port: str/bytes as service name, int as port number
2875 let port_encoded: Option<String> = match opts.port.as_ref() {
2876 Some(Either::A(sb)) => {
2877 let port_str = match sb {
2878 ArgStrOrBytesLike::Str(s) => {
2879 // For str, check for surrogates and raise UnicodeEncodeError if found
2880 s.to_str()
2881 .ok_or_else(|| vm.new_unicode_encode_error("surrogates not allowed"))?
2882 .to_owned()
2883 }
2884 ArgStrOrBytesLike::Buf(b) => {
2885 // For bytes, check if it's valid UTF-8
2886 let bytes = b.borrow_buf();
2887 core::str::from_utf8(&bytes)
2888 .map_err(|_| vm.new_unicode_decode_error("port is not utf8"))?
2889 .to_owned()
2890 }
2891 };
2892 Some(port_str)
2893 }
2894 Some(Either::B(i)) => Some(i.to_string()),
2895 None => None,
2896 };
2897 let port = port_encoded.as_deref();
2898
2899 let addrs = dns_lookup::getaddrinfo(host, port, Some(hints))

Callers 2

getnameinfoFunction · 0.70
get_addrFunction · 0.70

Calls 13

convert_socket_errorFunction · 0.85
get_ip_addr_tupleFunction · 0.85
encode_textMethod · 0.80
ok_or_elseMethod · 0.80
to_strMethod · 0.80
to_stringMethod · 0.80
SomeClass · 0.50
as_refMethod · 0.45
to_ownedMethod · 0.45
as_bytesMethod · 0.45
borrow_bufMethod · 0.45
mapMethod · 0.45

Tested by

no test coverage detected