当前位置: 技术问答>linux和unix
请教C语言编程实现 static ip 掩码、网关 设
来源: 互联网 发布时间:2016-06-04
本文导语: 通过UI设置IP Address, submask, gateway, dns,实现static 网络连接。 DHCP实现已经成功: if ( execl( DHCPCD_EXE_FULL_PATH, "dhcpcd", "-L", DHCPCD_CONFIG_DIR, "-R", "-Y", ...
通过UI设置IP Address, submask, gateway, dns,实现static 网络连接。 DHCP实现已经成功:
if ( execl( DHCPCD_EXE_FULL_PATH, "dhcpcd", "-L", DHCPCD_CONFIG_DIR,
"-R", "-Y", "-N", "-G",
"-n",
ifname, (char*)0 ) == -1 )
{
exit( 1 );
}
static 实现方式如下:
err = setIPAddr(s, &ifr, StaticIP);
if( !err)
{
err = setSubMask(s, &ifr, StaticSubMask);
}
if( !err)
{
char * StaticDstaddr = "192.168.1.0";
err = setDstaddr(s, &ifr, StaticDstaddr);
}
if( !err)
{
char * StaticBrdaddr = "192.168.1.255";
err = setBrdaddr(s, &ifr, StaticBrdaddr);
}
if(!err)
{
err = setMtu(s, &ifr, 1500);
}
if ( !err)
{
err = setGateWay(s, ifname, StaticGateWay);
}
////////////////////////////////////
INT32 setIPAddr(int sfd, struct ifreq *ifr, char * staticIPAddr)
{
struct sockaddr_in *p = (struct sockaddr_in *)&(ifr->ifr_addr);
p->sin_family = AF_INET;
inet_aton(staticIPAddr, &(p->sin_addr));
if(ioctl(sfd, SIOCSIFADDR, (caddr_t)ifr) ifr_addr);
p->sin_family = AF_INET;
inet_aton(staticSubMask, &(p->sin_addr));
if(ioctl(sfd, SIOCSIFNETMASK, (caddr_t)ifr) ifr_addr);
p->sin_family = AF_INET;
inet_aton(staticDstaddr, &(p->sin_addr));
if(ioctl(sfd, SIOCSIFDSTADDR, (caddr_t)ifr) ifr_addr);
p->sin_family = AF_INET;
inet_aton(staticBrdaddr, &(p->sin_addr));
if(ioctl(sfd, SIOCSIFBRDADDR, (caddr_t)ifr) ifr_addr);
p->sin_family = AF_INET;
ifr->ifr_mtu = staticMtu;
if(ioctl(sfd, SIOCSIFMTU, (caddr_t)ifr)
if ( execl( DHCPCD_EXE_FULL_PATH, "dhcpcd", "-L", DHCPCD_CONFIG_DIR,
"-R", "-Y", "-N", "-G",
"-n",
ifname, (char*)0 ) == -1 )
{
exit( 1 );
}
static 实现方式如下:
err = setIPAddr(s, &ifr, StaticIP);
if( !err)
{
err = setSubMask(s, &ifr, StaticSubMask);
}
if( !err)
{
char * StaticDstaddr = "192.168.1.0";
err = setDstaddr(s, &ifr, StaticDstaddr);
}
if( !err)
{
char * StaticBrdaddr = "192.168.1.255";
err = setBrdaddr(s, &ifr, StaticBrdaddr);
}
if(!err)
{
err = setMtu(s, &ifr, 1500);
}
if ( !err)
{
err = setGateWay(s, ifname, StaticGateWay);
}
////////////////////////////////////
INT32 setIPAddr(int sfd, struct ifreq *ifr, char * staticIPAddr)
{
struct sockaddr_in *p = (struct sockaddr_in *)&(ifr->ifr_addr);
p->sin_family = AF_INET;
inet_aton(staticIPAddr, &(p->sin_addr));
if(ioctl(sfd, SIOCSIFADDR, (caddr_t)ifr) ifr_addr);
p->sin_family = AF_INET;
inet_aton(staticSubMask, &(p->sin_addr));
if(ioctl(sfd, SIOCSIFNETMASK, (caddr_t)ifr) ifr_addr);
p->sin_family = AF_INET;
inet_aton(staticDstaddr, &(p->sin_addr));
if(ioctl(sfd, SIOCSIFDSTADDR, (caddr_t)ifr) ifr_addr);
p->sin_family = AF_INET;
inet_aton(staticBrdaddr, &(p->sin_addr));
if(ioctl(sfd, SIOCSIFBRDADDR, (caddr_t)ifr) ifr_addr);
p->sin_family = AF_INET;
ifr->ifr_mtu = staticMtu;
if(ioctl(sfd, SIOCSIFMTU, (caddr_t)ifr)