xref: /aosp_15_r20/external/crosvm/tests/plugin_net_config.c (revision bb4ee6a4ae7042d18b07a98463b9c8b875e44b39)
1 /*
2  * Copyright 2018 The ChromiumOS Authors
3  * Use of this source code is governed by a BSD-style license that can be
4  * found in the LICENSE file.
5  */
6 
7 #include <arpa/inet.h>
8 #include <linux/if_tun.h>
9 #include <sys/ioctl.h>
10 
11 #include <errno.h>
12 #include <stdint.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <unistd.h>
17 
18 #include "crosvm.h"
19 
20 /*
21  * These must match the network arguments supplied to the plugin in plugins.rs.
22  * IPv4 addresses here are in host-native byte order.
23  */
24 const uint32_t expected_ip = 0x64735c05; // 100.115.92.5
25 const uint32_t expected_netmask = 0xfffffffc; // 255.255.255.252
26 const uint8_t expected_mac[] = {0xde, 0x21, 0xe8, 0x47, 0x6b, 0x6a};
27 
main(int argc,char ** argv)28 int main(int argc, char** argv) {
29     struct crosvm *crosvm;
30     struct crosvm_net_config net_config;
31     int ret = crosvm_connect(&crosvm);
32 
33     if (ret) {
34         fprintf(stderr, "failed to connect to crosvm: %d\n", ret);
35         return 1;
36     }
37 
38     ret = crosvm_net_get_config(crosvm, &net_config);
39     if (ret) {
40         fprintf(stderr, "failed to get crosvm net config: %d\n", ret);
41         return 1;
42     }
43 
44     if (net_config.tap_fd < 0) {
45         fprintf(stderr, "fd %d is < 0\n", net_config.tap_fd);
46         return 1;
47     }
48 
49     unsigned int features;
50     if (ioctl(net_config.tap_fd, TUNGETFEATURES, &features) < 0) {
51         fprintf(stderr,
52                 "failed to read tap(fd: %d) features: %s\n",
53                 net_config.tap_fd,
54                 strerror(errno));
55         return 1;
56     }
57 
58     if (net_config.host_ip != htonl(expected_ip)) {
59         char ip_addr[INET_ADDRSTRLEN];
60         inet_ntop(AF_INET, &net_config.host_ip, ip_addr, sizeof(ip_addr));
61         fprintf(stderr, "ip %s != 100.115.92.5\n", ip_addr);
62         return 1;
63     }
64 
65     if (net_config.netmask != htonl(expected_netmask)) {
66         char netmask[INET_ADDRSTRLEN];
67         inet_ntop(AF_INET, &net_config.netmask, netmask, sizeof(netmask));
68         fprintf(stderr, "netmask %s != 255.255.255.252\n", netmask);
69         return 1;
70     }
71 
72     if (memcmp(net_config.host_mac_address,
73                expected_mac,
74                sizeof(expected_mac)) != 0) {
75         fprintf(stderr,
76                 "mac %02X:%02X:%02X:%02X:%02X:%02X != de:21:e8:47:6b:6a\n",
77                 net_config.host_mac_address[0],
78                 net_config.host_mac_address[1],
79                 net_config.host_mac_address[2],
80                 net_config.host_mac_address[3],
81                 net_config.host_mac_address[4],
82                 net_config.host_mac_address[5]);
83         return 1;
84     }
85 
86     return 0;
87 }
88