diff options
author | Damien George <damien@micropython.org> | 2024-08-03 16:06:52 +1000 |
---|---|---|
committer | Damien George <damien@micropython.org> | 2024-08-28 12:28:58 +1000 |
commit | c8385ef75aea929e7175173d3190dd787f37c8e4 (patch) | |
tree | 538f2fc0aefd4cece62cb83e76cd1b317cdf7838 /examples/network/http_client.py | |
parent | d9a0fdda9a7b0db55c1115b55bb1b83cd5ce739c (diff) | |
download | micropython-c8385ef75aea929e7175173d3190dd787f37c8e4.tar.gz micropython-c8385ef75aea929e7175173d3190dd787f37c8e4.zip |
examples/network: Support IPv4 and IPv6 in HTTP client examples.
The main changes here are to pass the address family and socket type to
`getaddrinfo()`, and then use the result of the address lookup when
creating the socket, so it has the correct address family.
This allows both IPv4 and IPv6 to work, because the socket is created with
the correct AF_INETx type for the address.
Also add some more comments to the examples to explain what's going on.
Fixes issue #15580.
Signed-off-by: Damien George <damien@micropython.org>
Diffstat (limited to 'examples/network/http_client.py')
-rw-r--r-- | examples/network/http_client.py | 32 |
1 files changed, 26 insertions, 6 deletions
diff --git a/examples/network/http_client.py b/examples/network/http_client.py index 661c286b70..879cddcd81 100644 --- a/examples/network/http_client.py +++ b/examples/network/http_client.py @@ -1,16 +1,35 @@ -import socket +# Very simple HTTP client example: +# - Connects to a server. +# - Sends a HTTP request. +# - Reads the result. +# +# This example works in both MicroPython and CPython. +# +# To implement an HTTP client using less code, use mip to install the requests package: +# https://github.com/micropython/micropython-lib/tree/master/python-ecosys/requests +import socket -def main(use_stream=False): - s = socket.socket() - ai = socket.getaddrinfo("google.com", 80) +# `addr_family` selects IPv4 vs IPv6: 0 means either, or use +# socket.AF_INET or socket.AF_INET6 to select a particular one. +def main(domain, addr_family=0, use_stream=False): + # Lookup the server address, for the given family and socket type. + ai = socket.getaddrinfo(domain, 80, addr_family, socket.SOCK_STREAM) print("Address infos:", ai) - addr = ai[0][-1] + # Select the first address. + ai = ai[0] + + # Create a socket with the server's family, type and proto. + s = socket.socket(ai[0], ai[1], ai[2]) + + # Connect to the server. + addr = ai[-1] print("Connect address:", addr) s.connect(addr) + # Send request and read response. if use_stream: # MicroPython socket objects support stream (aka file) interface # directly, but the line below is needed for CPython. @@ -21,7 +40,8 @@ def main(use_stream=False): s.send(b"GET / HTTP/1.0\r\n\r\n") print(s.recv(4096)) + # Close the socket. s.close() -main() +main("google.com") |