欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c/c++ 网络编程 UDP 改变IP地址

程序员文章站 2022-03-03 08:37:17
网络编程 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

c/c++ 网络编程 UDP 改变IP地址

本人微信:xiaoshitou5854