blob: b1010fc7555e565630e6ddce2fdd18e7d2f22338 [file] [log] [blame]
wangyouqiang387f7f22024-03-18 14:48:48 +08001
2//mdio eth0 1 读取phy寄存器1的数值
3//mdio eth0 0 0x1120 将0x1120写入 phy寄存器1
4
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8#include <linux/mii.h>
9#include <sys/types.h>
10#include <sys/socket.h>
11#include <sys/ioctl.h>
12#include <net/if.h>
13#include <linux/sockios.h>
14#include <linux/types.h>
15#include <netinet/in.h>
16#include <unistd.h>
17
18
19#define reteck(ret) \
20 if(ret < 0){ \
21 printf("%m! \"%s\" : line: %d\n", __func__, __LINE__); \
22 goto lab; \
23 }
24
25#define help() \
26 printf("mdio:\n"); \
27 printf("read operation: mdio reg_addr\n"); \
28 printf("write operation: mdio reg_addr value\n"); \
29 printf("For example:\n"); \
30 printf("mdio eth0 1\n"); \
31 printf("mdio eth0 0 0x12\n\n"); \
32 exit(0);
33
34int sockfd;
35
36int main(int argc, char *argv[]){
37
38 if(argc == 1 || !strcmp(argv[1], "-h")){
39 help();
40 }
41
42 struct mii_ioctl_data *mii = NULL;
43 struct ifreq ifr;
44 int ret;
45
46 memset(&ifr, 0, sizeof(ifr));
47 strncpy(ifr.ifr_name, argv[1], IFNAMSIZ - 1);
48
49 sockfd = socket(PF_LOCAL, SOCK_DGRAM, 0);
50 reteck(sockfd);
51
52 //get phy address in smi bus
53 ret = ioctl(sockfd, SIOCGMIIPHY, &ifr);
54 reteck(ret);
55
56 mii = (struct mii_ioctl_data*)&ifr.ifr_data;
57
58 if(argc == 3){
59
60 mii->reg_num = (uint16_t)strtoul(argv[2], NULL, 0);
61
62 ret = ioctl(sockfd, SIOCGMIIREG, &ifr);
63 reteck(ret);
64
65 printf("read phy addr: 0x%x reg: 0x%x value : 0x%x\n", mii->phy_id, mii->reg_num, mii->val_out);
66
67 if (mii->reg_num == 0x1)
68 {
69 printf("Link Status\n");
70
71 if(mii->val_out& 0x0004){
72 printf("link is up\n");
73 }else{
74 printf("link is down\n");
75 }
76 }
77 }else if(argc == 4){
78
79 mii->reg_num = (uint16_t)strtoul(argv[2], NULL, 0);
80 mii->val_in = (uint16_t)strtoul(argv[3], NULL, 0);
81
82 ret = ioctl(sockfd, SIOCSMIIREG, &ifr);
83 reteck(ret);
84
85 printf("write phy addr: 0x%x reg: 0x%x value : 0x%x\n", mii->phy_id, mii->reg_num, mii->val_in);
86 }
87
88 lab:
89 close(sockfd);
90 return 0;
91}