c/c++ 网络编程 UDP 改变IP地址
程序员文章站
2022-06-15 15:06:56
网络编程 UDP 改变IP地址 在程序里动态改变主机的IP地址 1,改变ipv4的地址 "github源代码" 2,改变ipv6的地址 c++ include include include include include include include include include struct ......
网络编程 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; }
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; }
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; }
c/c++ 学习互助qq群:877684253
本人微信:xiaoshitou5854
上一篇: ZROJ#397. 【18提高7】模仿游戏(爆搜)
下一篇: jQuery实现简单三级联动效果