linux 里通过想写一个c语言的文件 ,通过执行文件可以修改ifcfg-eth0中的IPADDR的值
发布网友
发布时间:2022-05-05 16:58
我来回答
共1个回答
热心网友
时间:2023-10-09 02:58
//获取本机IP地址函数
view plaincopy to clipboardprint?
01.QString GetLocalIp()
02.{
03.
04. int sock_get_ip;
05. char ipaddr[50];
06.
07. struct sockaddr_in *sin;
08. struct ifreq ifr_ip;
09.
10. if ((sock_get_ip=socket(AF_INET, SOCK_STREAM, 0)) == -1)
11. {
12. printf("socket create failse...GetLocalIp!\n");
13. return "";
14. }
15.
16. memset(&ifr_ip, 0, sizeof(ifr_ip));
17. strncpy(ifr_ip.ifr_name, "eth0", sizeof(ifr_ip.ifr_name) - 1);
18.
19. if( ioctl( sock_get_ip, SIOCGIFADDR, &ifr_ip) < 0 )
20. {
21. return "";
22. }
23. sin = (struct sockaddr_in *)&ifr_ip.ifr_addr;
24. strcpy(ipaddr,inet_ntoa(sin->sin_addr));
25.
26. printf("local ip:%s \n",ipaddr);
27. close( sock_get_ip );
28.
29. return QString( ipaddr );
30.}
QString GetLocalIp()
{
int sock_get_ip;
char ipaddr[50];
struct sockaddr_in *sin;
struct ifreq ifr_ip;
if ((sock_get_ip=socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("socket create failse...GetLocalIp!\n");
return "";
}
memset(&ifr_ip, 0, sizeof(ifr_ip));
strncpy(ifr_ip.ifr_name, "eth0", sizeof(ifr_ip.ifr_name) - 1);
if( ioctl( sock_get_ip, SIOCGIFADDR, &ifr_ip) < 0 )
{
return "";
}
sin = (struct sockaddr_in *)&ifr_ip.ifr_addr;
strcpy(ipaddr,inet_ntoa(sin->sin_addr));
printf("local ip:%s \n",ipaddr);
close( sock_get_ip );
return QString( ipaddr );
}
//修改本机IP地址的函数
int SetLocalIp( const char *ipaddr )
{
int sock_set_ip;
struct sockaddr_in sin_set_ip;
struct ifreq ifr_set_ip;
bzero( &ifr_set_ip,sizeof(ifr_set_ip));
if( ipaddr == NULL )
return -1;
if(sock_set_ip = socket( AF_INET, SOCK_STREAM, 0 ) == -1);
{
perror("socket create failse...SetLocalIp!\n");
return -1;
}
memset( &sin_set_ip, 0, sizeof(sin_set_ip));
strncpy(ifr_set_ip.ifr_name, "eth0", sizeof(ifr_set_ip.ifr_name)-1);
sin_set_ip.sin_family = AF_INET;
sin_set_ip.sin_addr.s_addr = inet_addr(ipaddr);
memcpy( &ifr_set_ip.ifr_addr, &sin_set_ip, sizeof(sin_set_ip));
if( ioctl( sock_set_ip, SIOCSIFADDR, &ifr_set_ip) < 0 )
{
perror( "Not setup interface\n");
return -1;
}
//设置激活标志
ifr_set_ip.ifr_flags |= IFF_UP |IFF_RUNNING;
//get the status of the device
if( ioctl( sock_set_ip, SIOCSIFFLAGS, &ifr_set_ip ) < 0 )
{
perror("SIOCSIFFLAGS");
return -1;
}
close( sock_set_ip );
return 0;
}