Notes Linux C language implementation of static IP address, mask, gateway settings

Source: Internet
Author: User
Tags sin socket error

#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <error.h>
#include <net/route.h> int setifaddr (char *ifname, Char *ipaddr, char *mask,char *gateway)
{
int fd;
int RC;
struct ifreq IFR;
struct sockaddr_in *sin;
struct Rtentry RT;
   
FD = socket (af_inet, SOCK_DGRAM, 0);
if (FD < 0)
    {
perror ("socket error");
return-1;
    }memset (&ifr,0,sizeof (IFR));
strcpy (ifr.ifr_name,ifname);
sin = (struct sockaddr_in*) &ifr.ifr_addr;
sin->sin_family = af_inet;   
//ipaddr
if (Inet_aton (ipaddr,& (sin->sin_addr)) < 0)
    {    
perror ("Inet_aton error");
return-2;
    }   
   
if (IOCTL (FD,SIOCSIFADDR,&IFR) < 0)
    {    
perror ("IOCTL siocsifaddr error");
return-3;
    }
//netmask
if (Inet_aton (mask,& (sin->sin_addr)) < 0)
    {    
perror ("Inet_pton error");
return-4;
    }   
if (IOCTL (FD, Siocsifnetmask, &IFR) < 0)
    {
perror ("IOCTL");
return-5;
    }
//gateway
memset (&rt, 0, sizeof (struct rtentry));
memset (sin, 0, sizeof (struct sockaddr_in));
sin->sin_family = af_inet;
sin->sin_port = 0;if (Inet_aton (Gateway, &sin->sin_addr) <0)
    {
printf ("Inet_aton error\n");
    }
memcpy (&rt.rt_gateway, sin, sizeof (struct sockaddr_in));
(struct sockaddr_in *) &rt.rt_dst)->sin_family=af_inet;
(struct sockaddr_in *) &rt.rt_genmask)->sin_family=af_inet;
rt.rt_flags = Rtf_gateway;if (IOCTL (FD, SIOCADDRT, &rt) <0)
    {
Zerror ("IOCTL (SIOCADDRT) error in set_default_route\n");
Close (FD);
return-1;
    }Close (FD);
return RC;

}

Notes Linux C language implementation of static IP address, mask, gateway settings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.