Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
849 views
in Technique[技术] by (71.8m points)

networking - Linux : how to set default route from C?

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). Also can you set the default route without specifying the gateway IP address? In my application I want to make either ppp0 or eth0 the default route, depending on whether the cable is plugged into eth0 or not.

Thanks, Fred

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
");
      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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...