Python get local IPv4

background

Python implements a tcp server. However, every time you connect to a different external network, IPv4 will change, so it is inconvenient whether it is hard-coded or written in a configuration file. Then directly use the code to obtain the local when running the program. IPv4 naturally becomes a requirement

the code

import socket

ipv4s=socket.gethostbyname_ex(socket.gethostname())[2]
print(ipv4s)

result

Notice

The result is a list. If you have a virtual machine installed on your machine, there may be other virtual ipv4, which requires you to do other algorithms for screening.

Guess you like

Origin blog.csdn.net/qq_36694133/article/details/127084294