通过 ioctl 配置接口的 IP 地址

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <linux/if.h>
#include <linux/if_ether.h>
#include <linux/if_arp.h>
#include <linux/netlink.h>
#include <linux/route.h>
#include <linux/ipv6_route.h>
#include <linux/rtnetlink.h>
#include <linux/sockios.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>

#include "ipconfig.h"

#define INTERFACE	"wlan0"

int skfd = -1;

int main()
{
  NMDBG("ipconfig...");
  uint32_t ip = 0x1f2ba8c0;
  uint8_t *p = (uint8_t*)&ip;
  struct ifreq ifr;
  struct sockaddr_in sin;
  
  strncpy(ifr.ifr_name, INTERFACE, IFNAMSIZ);
  memset(&sin, 0, sizeof(struct sockaddr));
  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = ip;
  memcpy(&ifr.ifr_addr, &sin, sizeof(struct sockaddr));
  skfd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
  if (ioctl(skfd, SIOCSIFADDR, &ifr) < 0)
  {
    NMDBG("failed to set ip address %u.%u.%u.%u to %s, %s",
        p[0], p[1], p[2], p[3], INTERFACE, strerror(errno));
    return -1;
  }

  return 0;
}

 

上一篇:简单实现一个linux下的socket server 和 client


下一篇:多线程服务器的实现