如何从C在linux设置IP地址 [英] How to set the IP address from C in linux

查看:109
本文介绍了如何从C在linux设置IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过使用strace的和ifconfig,我发现我可以设置IP地址这种方式:

By using strace and ifconfig, I found that I can set the IP address this way:

#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <string.h>

int main(int argc, const char *argv[]) {
    struct ifreq ifr;
    const char * name = "eth1";
    int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);

    strncpy(ifr.ifr_name, name, IFNAMSIZ);

    ifr.ifr_addr.sa_family = AF_INET;
    inet_pton(AF_INET, "10.12.0.1", ifr.ifr_addr.sa_data + 2);
    ioctl(fd, SIOCSIFADDR, &ifr);

    inet_pton(AF_INET, "255.255.0.0", ifr.ifr_addr.sa_data + 2);
    ioctl(fd, SIOCSIFNETMASK, &ifr);

    ioctl(fd, SIOCGIFFLAGS, &ifr);
    strncpy(ifr.ifr_name, name, IFNAMSIZ);
    ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);

    ioctl(fd, SIOCSIFFLAGS, &ifr);

    return 0;
}

但我不是很高兴与此解决方案:

But I am not very happy with this solution:

inet_pton(AF_INET, "10.12.0.1", ifr.ifr_addr.sa_data + 2);

什么是这样做的正确的方式?

What is the "right" way of doing this?

推荐答案

正确的方式对IPv4不用魔法+2:

The "correct" way for IPv4 without magic +2:

struct sockaddr_in* addr = (struct sockaddr_in*)&ifr.ifr_addr;
inet_pton(AF_INET, "10.12.0.1", &addr->sin_addr);

要使用IPv6,将其转换为体sockaddr_in6

To use IPv6, cast it to sockaddr_in6

这篇关于如何从C在linux设置IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆