Linux : how to set default route from C?

后端 未结 2 1407
后悔当初
后悔当初 2021-01-24 11:06

How can I set (and replace the existing) default network route from a C program? I\'d like to do it without shell commands if possible (this is a low memory embedded system).

相关标签:
2条回答
  • 2021-01-24 11:45

    You can make IOCTL calls to set the default route from a C program.

    void main()
    {
       int sockfd;
       struct rtentry rt;
    
       sockfd = socket(AF_INET, SOCK_DGRAM, 0);
       if (sockfd == -1)
       {
          perror("socket creation failed\n");
          return;
       }
    
       struct sockaddr_in *sockinfo = (struct sockaddr_in *)&rt.rt_gateway;
       sockinfo->sin_family = AF_INET;
       sockinfo->sin_addr.s_addr = inet_addr("Your Address");
    
       sockinfo = (struct sockaddr_in *)&rt.rt_dst;
       sockinfo->sin_family = AF_INET;
       sockinfo->sin_addr.s_addr = INADDR_ANY;
    
       sockinfo = (struct sockaddr_in *)&rt.rt_genmask;
       sockinfo->sin_family = AF_INET;
       sockinfo->sin_addr.s_addr = INADDR_ANY;
    
       rt.rt_flags = RTF_UP | RTF_GATEWAY;
       rt.rt_dev = "eth0";
    
       if(ioctl(sockfd, SIOCADDRT, &rt) < 0 )
           perror("ioctl");
    
       return;
    }
    
    0 讨论(0)
  • 2021-01-24 12:03

    You could strace the route command you are wanting to mimic. This gives you the relevant syscalls useful to change routing.

    You may be interested by the proc(5) interface, e.g. its /proc/net/route pseudo-file.

    See also ip(7).

    0 讨论(0)
提交回复
热议问题