]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
sd_device: introduce device_get_ifname()
authorYu Watanabe <watanabe.yu+github@gmail.com>
Wed, 5 Mar 2025 22:03:45 +0000 (07:03 +0900)
committerYu Watanabe <watanabe.yu+github@gmail.com>
Wed, 12 Mar 2025 16:08:57 +0000 (01:08 +0900)
sd-device replaces '!' in sysname with '/'. Hence, sysname and ifname
may be different. Let's get network interface name through INTERFACE
property.

src/libsystemd/sd-device/device-private.h
src/libsystemd/sd-device/sd-device.c
src/libsystemd/sd-device/test-sd-device.c

index 7d925aa581dd29efe2cd5022228ae4347a8231d5..dea772863398b92bb5253b145f9a3fe2cffc4a0f 100644 (file)
@@ -21,6 +21,7 @@ int device_opendir(sd_device *device, const char *subdir, DIR **ret);
 int device_get_sysnum_unsigned(sd_device *device, unsigned *ret);
 int device_get_property_bool(sd_device *device, const char *key);
 int device_get_property_int(sd_device *device, const char *key, int *ret);
+int device_get_ifname(sd_device *device, const char **ret);
 int device_get_sysattr_int(sd_device *device, const char *sysattr, int *ret_value);
 int device_get_sysattr_unsigned_full(sd_device *device, const char *sysattr, unsigned base, unsigned *ret_value);
 static inline int device_get_sysattr_unsigned(sd_device *device, const char *sysattr, unsigned *ret_value) {
index 181a9256dd2df44949d2c0068c1e8f2c40665bd1..b7b308b390880f3416b675c99f854719c22c60c1 100644 (file)
@@ -871,6 +871,21 @@ _public_ int sd_device_get_ifindex(sd_device *device, int *ifindex) {
         return 0;
 }
 
+int device_get_ifname(sd_device *device, const char **ret) {
+        int r;
+
+        assert_return(device, -EINVAL);
+
+        /* First, check if the device is a network interface. */
+        r = sd_device_get_ifindex(device, NULL);
+        if (r < 0)
+                return r;
+
+        /* The sysname and ifname may be different, as '!' in sysname are replaced with '/'.
+         * For network interfaces, we can use INTERFACE property. */
+        return sd_device_get_property_value(device, "INTERFACE", ret);
+}
+
 _public_ int sd_device_new_from_device_id(sd_device **ret, const char *id) {
         int r;
 
index 705a10d159fc8e4b6bf1da06a1e1529572e56c07..b2b04562cde36cf9c7d0fbd0b9fd0e7da6547d1e 100644 (file)
@@ -52,6 +52,14 @@ static void test_sd_device_one(sd_device *d) {
         else {
                 ASSERT_GT(ifindex, 0);
 
+                const char *ifname;
+                ASSERT_OK(device_get_ifname(d, &ifname));
+                ASSERT_NOT_NULL(endswith(syspath, ifname));
+                if (strchr(sysname, '/'))
+                        ASSERT_FALSE(streq(ifname, sysname));
+                else
+                        ASSERT_STREQ(ifname, sysname);
+
                 r = sd_device_new_from_ifindex(&dev, ifindex);
                 if (r < 0) {
                         ASSERT_ERROR(r, ENODEV);