简体   繁体   中英

Trying to set the IP address from C program

I am trying to change the IP address of the raspberry pi with the C code. But when i run the code, i can connect to the raspberry pi with the new IP i gave. But if i restart raspberry pi or network service, it goes back to its old IP.

#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 = "eth0";
    int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);

    strncpy(ifr.ifr_name, name, IFNAMSIZ);

    ifr.ifr_addr.sa_family = AF_INET;

    struct sockaddr_in* addr = (struct sockaddr_in*)&ifr.ifr_addr;
    inet_pton(AF_INET, "192.168.4.27", &addr->sin_addr);
    ioctl(fd, SIOCSIFADDR, &ifr);

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

    ioctl(fd, SIOCSIFFLAGS, &ifr);

    return 0;
}

Normally the raspberry pi's address is 192.168.4.28, I want to replace it with 192.168.4.27. When i run it, i don't get any errors and i can connect with 192.168.4.27. Also, i can connect with 192.168.4.28. So can connect both IP. When i type "ifconfig" i can see that the ip has changed to 192.168.4.27. When i type "ip addr" i get this;

eth0 :

inet 192.168.4.27/24 scope global noprefixroute eth0

inet 192.168.4.28/24 scope global secondary noprefixroute eth0

In short, how can i ensure that the IP i want to give is primary and permanent.

Fixing the IP address as you do in your example will only change the adaptor's 'current' IP.

When Raspberry boots up it sets the IP address from the init scripts, and that is what you need to modify in order to make the change permanent.

What kind of scripts it uses depends on the distribution you are using, probably systemd. You could make a program to use the system tools to set up that information, or to modify the text files.

In case of systemd scripts/files, they are usually at /etc/systemd/network, here is a manual page from systemd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM