linux 函数路由代码

作者: admin 分类: linux 发布时间: 2010-11-15 13:33 ė 6 没有评论
 #include <sys/ioctl.h>
 #include <string.h>
 #include <stdlib.h>
 #include <errno.h>
 #include <stdio.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <arpa/inet.h>
 #include <unistd.h>
 #include <net/route.h>
 #define E_ERR   1
 
int main()
 {
 
     struct rtentry rt;
     struct sockaddr_in my_addr;
 
     int sock_fd;
     char devi[] = “eth0”;
 
     if ((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
     {
         perror(“socket”);
         close(sock_fd);
         return E_ERR;
     }
 
     rt.rt_flags = (unsigned short)(RTF_UP | RTF_GATEWAY | RTF_DEFAULT | RTF_HOST);
     my_addr.sin_family = AF_INET;
 
     inet_aton(“10.10.91.1”, &my_addr.sin_addr);
     memcpy(&rt.rt_dst, &my_addr, sizeof(struct sockaddr));
 
     inet_aton(“192.168.1.1”, &my_addr.sin_addr);
     memcpy(&rt.rt_gateway, &my_addr, sizeof(struct sockaddr));
 
     inet_aton(“255.255.255.255”, &my_addr.sin_addr);
     memcpy(&rt.rt_genmask, &my_addr, sizeof(struct sockaddr));
 
     rt.rt_dev = devi;
 
     if (ioctl(sock_fd, SIOCADDRT, &rt) < 0)
     {
         perror(“SIOCADDRT”);
         close(sock_fd);
         return E_ERR;
     }
     return 0;
 }

本文出自 小Q,转载时请注明出处及相应链接。

本文永久链接: http://www.linuxqq.com/archives/245.html

0
更多
Ɣ回顶部