Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

networking - Python: check whether a network interface is up

In Python, is there a way to detect whether a given network interface is up?

In my script, the user specifies a network interface, but I would like to make sure that the interface is up and has been assigned an IP address, before doing anything else.

I'm on Linux and I am root.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The interface can be configured with an IP address and not be up so the accepted answer is wrong. You actually need to check /sys/class/net/<interface>/flags. If the content is in the variable flags, flags & 0x1 is whether the interface is up or not.

Depending on the application, the /sys/class/net/<interface>/operstate might be what you really want, but technically the interface could be up and the operstate down, e.g. when no cable is connected.

All of this is Linux-specific of course.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...