ioctl 开启/关闭网络接口

int interface_up (char * interface_name)
{
    int s;
    if((s = socket(PF_INET,SOCK_STREAM,0)) < 0)
    {
        perror("Socket");
        return -1;
    }

    struct ifreq ifr;
    strcpy(ifr.ifr_name,interface_name);
    short flag;
    flag = IFF_UP;

    if(ioctl(s,SIOCGIFFLAGS,&ifr) < 0)
    {
        perror("ioctl");
        return -1;
    }


    ifr.ifr_ifru.ifru_flags |= flag;
    if(ioctl(s,SIOCSIFFLAGS,&ifr) < 0)
    {
        perror("ioctl");
        return -1;
    }
    return 0;
}

int interface_down (char * interface_name)
{
    if(strcmp(interface_name,"lo") == 0)
    {
        printf("You can't pull down interface lo/n");
        return 0;
    }


    int s;

    if((s = socket(PF_INET,SOCK_STREAM,0)) < 0)
    {
        perror("Socket");
        return -1;
    }

    struct ifreq ifr;
    strcpy(ifr.ifr_name,interface_name);
    short flag;
    flag = ~IFF_UP;
    if(ioctl(s,SIOCGIFFLAGS,&ifr) < 0)
    {
        perror("ioctl");
        return -1;
    }
    ifr.ifr_ifru.ifru_flags &= flag;
    if(ioctl(s,SIOCSIFFLAGS,&ifr) < 0)
    {
        perror("ioctl");
        return -1;
    }
    return 0;
}

你可能感兴趣的:(socket,struct,网络,Stream,UP,interface)