简体   繁体   中英

Get Ethernet adapter IPv4 address without using external libraries

I have 2 computers connected with crossover cable and first time I need to start PC1 as server and PC2 as client and then second time PC2 as server and PC1 as client. I use UDP socket and it is on Windows. So I cant just put IP in code, I need the server code to get the IP automatically.

I tried this:

hostname = socket.gethostname()    
IPAddr = socket.gethostbyname(hostname)

But this gives me wrong IP. I need the IP address that I see when I check Ethernet adapter Ethernet in ipconfig/all.

I'm not sure if you understand me sorry. English is not my best skill.

You could try using the netifaces package. Docs are here .

import netifaces

ip = netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr']
print(ip)

eth0 is just an example, you can get the actual interface name from ipconfig

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM