如何更改默认网关vie C [英] How to Change default gateway vie C

查看:103
本文介绍了如何更改默认网关vie C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用C语言编写一个程序,该程序将更改默认网关.

I am trying to write a program in C that will change the default gateway.

我已运行以下代码: Linux:如何设置默认值从C出发的路线?此处提供的代码无法正常运行.它将在其旁边添加具有高度量标准编号的默认网关.我阅读了有关度量标准的数字,但这显然不是我的目标.我想用我自己的一个交换当前的默认地址.

I have run the following code: Linux : how to set default route from C? The code presented here is not working as i would imagine. It adds a default gateway with a high metric number next to it. I read about the metric numbers but this is clearly not my goal. I would like to swap the current default address with one of my own.

如果您添加一些代码,由于它是首次使用ioctl,因此在此附近的解释也将不胜感激.不是很熟悉它的工作原理,或者为什么要添加很多东西来定义它.

If you add some code, an explanation near it would also be much appreciated since it's the first time working with ioctl. Not that familiar with how it work's or why so many things needed to be added to define it.

P.S.请避免需要我打开文件或字符串操作的任何答复.预先谢谢你

P.S. please avoid any responses that require me to open files or string manipulations. Thank you in advance

推荐答案

下面是一段代码,用于定义默认网关

Here is a piece of code to define the default gateway

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <net/route.h>
#include <sys/types.h>
#include <sys/ioctl.h>

int main(char** args) {
  int sockfd;
  struct rtentry route;
  struct sockaddr_in *addr;
  int err = 0;

  // create the socket
 if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)))<0){
perror("socket");
exit(1);
}

  memset(&route, 0, sizeof(route));
  addr = (struct sockaddr_in*) &route.rt_gateway;
  addr->sin_family = AF_INET;
  addr->sin_addr.s_addr = inet_addr("192.168.2.1");
  addr = (struct sockaddr_in*) &route.rt_dst;
  addr->sin_family = AF_INET;
  addr->sin_addr.s_addr = INADDR_ANY;
  addr = (struct sockaddr_in*) &route.rt_genmask;
  addr->sin_family = AF_INET;
  addr->sin_addr.s_addr = INADDR_ANY;
  // You need to add the interface name to the request
  route.rt_flags = RTF_UP | RTF_GATEWAY;
  route.rt_metric = 0;
  if ((err = ioctl(sockfd, SIOCADDRT, &route)) != 0) {
    perror("SIOCADDRT failed");
    exit(1);
  }
}

它仅使用简单的IOCTL概念.如果您对这些概念有疑问,建议您查看以下链接: IOCTL手册页

It uses only simple IOCTL concepts. If you have problems with these notions I advise you to take a look at the link below : IOCTL Man Page

这篇关于如何更改默认网关vie C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆