网络编程 UDP 改变IP地址
在程序里动态改变主机的IP地址
1,改变ipv4的地址
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
int main(){
int fd;
ifreq ifr;
sockaddr_in *s_in;
fd = socket(AF_INET, SOCK_DGRAM, 0);
s_in = (sockaddr_in*)&ifr.ifr_addr;
s_in->sin_family = AF_INET;
s_in->sin_addr.s_addr = inet_addr("10.0.2.15");
strncpy(ifr.ifr_name, "enp0s3", IFNAMSIZ - 1);
if(ioctl(fd, SIOCSIFADDR, &ifr) != 0){
perror("ioctl");
return 1;
}
close(fd);
return 0;
}
github源代码
2,改变ipv6的地址
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
struct in6_ifreq{
struct in6_addr ifr6_addr;
u_int32_t ifr6_prefixlen;
int ifr6_ifindex;
};
int main(){
int fd;
in6_ifreq ifr;
int n;
fd = socket(AF_INET6, SOCK_DGRAM, 0);
memset(&ifr, 0, sizeof(ifr));
inet_pton(AF_INET6, "2003::1", &ifr.ifr6_addr);
ifr.ifr6_prefixlen = 64;
ifr.ifr6_ifindex = if_nametoindex("enp0s3");
n = ioctl(fd, SIOCSIFADDR, &ifr);
if(n < 0){
perror("ioctl");
return 1;
}
close(fd);
return 0;
}
github源代码
3,删除ipv6的地址
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
struct in6_ifreq{
struct in6_addr ifr6_addr;
u_int32_t ifr6_prefixlen;
int ifr6_ifindex;
};
int main(){
int fd;
in6_ifreq ifr;
int n;
fd = socket(AF_INET6, SOCK_DGRAM, 0);
memset(&ifr, 0, sizeof(ifr));
inet_pton(AF_INET6, "2003::1", &ifr.ifr6_addr);
ifr.ifr6_prefixlen = 64;
ifr.ifr6_ifindex = if_nametoindex("enp0s3");
n = ioctl(fd, SIOCDIFADDR, &ifr);
if(n < 0){
perror("ioctl");
return 1;
}
close(fd);
return 0;
}
github源代码
c/c++ 学习互助QQ群:877684253
本人微信:xiaoshitou5854