linux下C语言实现静态IP地址,网关的设置
2019-07-13 08:28发布
生成海报
#include
#include
#include
#include
#include
#include
#include
#include
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;
//IP地址
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;
}
//子网掩码
if(inet_aton(mask,&(sin->sin_addr)) < 0)
{
perror("inet_pton error");
return -4;
}
if(ioctl(fd, SIOCSIFNETMASK, &ifr) < 0)
{
perror("ioctl");
return -5;
}
//网关
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
" );
}
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
");
close(fd);
return -1;
}
close(fd);
return rc;
}
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮