How to detect the physical connected state of a network cable/connector?

后端 未结 15 1370
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 04:23

In a Linux environment, I need to detect the physical connected or disconnected state of an RJ45 connector to its socket. Preferably using BASH scripting only.

The

15条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 05:16

    On the low level, these events can be caught using rtnetlink sockets, without any polling. Side note: if you use rtnetlink, you have to work together with udev, or your program may get confused when udev renames a new network interface.

    The problem with doing network configurations with shell scripts is that shell scripts are terrible for event handling (such as a network cable being plugged in and out). If you need something more powerful, take a look at my NCD programming language, a programming language designed for network configurations.

    For example, a simple NCD script that will print "cable in" and "cable out" to stdout (assuming the interface is already up):

    process foo {
        # Wait for device to appear and be configured by udev.
        net.backend.waitdevice("eth0");
        # Wait for cable to be plugged in.
        net.backend.waitlink("eth0");
        # Print "cable in" when we reach this point, and "cable out"
        # when we regress.
        println("cable in");   # or pop_bubble("Network cable in.");
        rprintln("cable out"); # or rpop_bubble("Network cable out!");
                               # just joking, there's no pop_bubble() in NCD yet :)
    }
    

    (internally, net.backend.waitlink() uses rtnetlink, and net.backend.waitdevice() uses udev)

    The idea of NCD is that you use it exclusively to configure the network, so normally, configuration commands would come in between, such as:

    process foo {
        # Wait for device to appear and be configured by udev.
        net.backend.waitdevice("eth0");
        # Set device up.
        net.up("eth0");
        # Wait for cable to be plugged in.
        net.backend.waitlink("eth0");
        # Add IP address to device.
        net.ipv4.addr("eth0", "192.168.1.61", "24");
    }
    

    The important part to note is that execution is allowed to regress; in the second example, for instance, if the cable is pulled out, the IP address will automatically be removed.

提交回复
热议问题