无法从python设置默认网关

时间:2019-02-13 08:23:33

标签: python gateway ioctl

我已经编写了代码,以使用C中的ioctl来设置默认网关。我具有设置网关的功能和通常的主要功能。当我编译并运行代码时,它工作正常,但是当我将其转换为库并使用ctypes从python调用主函数时,ioctl调用将失败。为什么是这样?

注意:在使用ctypes方法之前,我尝试使用fcntlioctlsocket从python设置网关,但失败的原因是OSError说{ {1}}。

gateway.c

invalid arguments

net.py

int setDefaultGW( int sockfd, char* gatewatStr)
{

    struct sockaddr_in *dst, *gw, *mask;
    struct rtentry route;
    in_addr_t gip;

    fprintf( stderr,"socket %d\n", sockfd);
    fprintf( stderr,"Address %s\n", gatewatStr);
    gip = inet_addr(gatewatStr);
    fprintf( stderr,"Address %d\n", gip);

memset(&route,0,sizeof(struct rtentry));

dst = (struct sockaddr_in *)(&(route.rt_dst));
gw = (struct sockaddr_in *)(&(route.rt_gateway));
mask = (struct sockaddr_in *)(&(route.rt_genmask));

/* Make sure we're talking about IP here */
dst->sin_family = AF_INET;
gw->sin_family = AF_INET;
mask->sin_family = AF_INET;

/* Set up the data for adding the default route */
dst->sin_addr.s_addr = inet_addr("0.0.0.0");
gw->sin_addr.s_addr = gip;
mask->sin_addr.s_addr = inet_addr("0.0.0.0");
route.rt_metric = 100;
route.rt_flags = RTF_UP | RTF_GATEWAY;

/* Remove this route if it already exists */
ioctl(sockfd,SIOCDELRT,&route);

/* Add the default route */
if( ioctl(sockfd,SIOCADDRT,&route) < 0 )
{
    fprintf( stderr,"Adding default route: %d\n", errno);
    return -1;
}

fprintf( stdout,"Added default route successfully.\n" );
return 0;
}

int main(){

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1)
    {
        perror("socket creation failed\n");
        return;
    }
    setDefaultGW(sockfd, "192.168.6.1");
    return 0;
}

运行C二进制文件:

gatewayFun = ctypes.CDLL("./libgateway.so") 
gatewayFun.main()

运行python脚本:

./gateway                                                                                                               
socket 3
Address 192.168.6.1
Address 17213632
Added default route successfully.

0 个答案:

没有答案