#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/route.h>
#include <linux/if_vlan.h>
#include <linux/sockios.h>
#include <fcntl.h>
#include <errno.h>
#define MAX_BUF_SIZE 4096
void check_and_remove_interface(const char *if_name);
int remove_virtual_interface(const char *if_name);
void check_and_remove_interface(const char *if_name)
{
char buf[MAX_BUF_SIZE];
char name[IFNAMSIZ];
char eth[IFNAMSIZ];
int ret = -1;
FILE *fp;
fp = fopen("/proc/net/vlan/config", "r");
if (fp == NULL)
{
printf("fopen() error: %s\n", strerror(errno));
return;
}
while ((fgets(buf, sizeof(buf), fp)) != NULL)
{
char *pbegin = buf;
while (pbegin < buf + sizeof(buf) - 1 && *pbegin == ' ')
{
++pbegin;
}
memset(eth, '\0', sizeof(eth));
memset(name, '\0', sizeof(name));
char *pend = strchr(buf, '|');
char *prbegin = strrchr(buf, '|');
if (pend != NULL && prbegin != NULL && pend != prbegin)
{
--pend;
++prbegin;
}
else
{
continue;
}
while (pend > pbegin && isspace(*pend))
{
--pend;
}
while (prbegin < buf + sizeof(buf) - 1 && isspace(*prbegin))
{
++prbegin;
}
if (pbegin < pend && prbegin < buf + sizeof(buf) - strlen(if_name) - 1)
{
strncpy(name, pbegin, pend - pbegin + 1);
strncpy(eth, prbegin, strlen(if_name));
if (strcmp(eth, if_name) == 0)
{
ret = remove_virtual_interface(name);
if (ret == 0)
{
printf("Remove virtual interface %s successfully!\n", name);
}
else
{
printf("Remove virtual interface %s failed!\n", name);
}
}
}
}
fclose(fp);
}
int remove_virtual_interface(const char *if_name)
{
struct ifreq ifr;
struct vlan_ioctl_args args;
int sock, fd, ret;
fd = open("/proc/net/vlan/config", O_RDONLY);
if (fd < 0)
{
return -1;
}
close(fd);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
return -1;
}
strncpy(args.device1, if_name, sizeof(args.device1));
args.cmd = DEL_VLAN_CMD;
if (ioctl(sock, SIOCSIFVLAN, &args) < 0)
{
ret = -1;
}
else
{
ret = 0;
}
close(sock);
return ret;
}
int main()
{
check_and_remove_interface("eth0");
return 0;
}
Linux下删除virtual vlan interface
最新推荐文章于 2024-08-14 19:55:44 发布