如何使用C程序为计算机设置IP地址?
问题描述:
我有一个硬代码(C代码)来打印我的计算机IP地址,我会改变我的IP与一些要求,最后我可以在屏幕上打印更新的IP。现在的问题是,我需要将更改后的IP地址设置到我的电脑上。任何人都可以帮我设置一个新的IP地址给使用C语言作为平台的计算机。 我的硬代码和它的输出附在下面。如何使用C程序为计算机设置IP地址?
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <unistd.h>
#include <arpa/inet.h>
int main()
{
int n,chain=2,ADU=2,cam_port=2,IP=0,formulae,stream_num=3;
struct ifreq ifr;
char array[] = "eth0";
int int_val = 0;
int c = 0;
char *some_addr;
n = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name , array , IFNAMSIZ - 1);
ioctl(n, SIOCGIFADDR, &ifr);
close(n);
printf("IP Address is %s - %s\n" , array , inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
some_addr = inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr);
printf("The last character octet is %c%c%c\n", some_addr[11],some_addr[12],some_addr[13]);
for (c = 11; some_addr[c]!= '\0'; c++)
{
int_val = int_val * 10 + some_addr[c] - '0';
}
printf("int value = %d\n", int_val);
IP = int_val;
formulae=((chain-1)*128) + ((ADU-1)*32) + ((cam_port-1)*4) + (stream_num+1);
IP=formulae;
printf("updated IP is 239.192.140.%d\n",IP);
return 0;
}
输出:
的IP地址是eth0的 - 192.168.15.91
最后一个字符八位组是91
int值= 91
更新IP是239.192.140.168
答
你已经在使用ioctl(SIOCGIFADDR
来获取接口地址,所以一旦你改变它在ifreq
结构体,然后可以执行ioctl(SIOCSIFADDR
来设置它。不过,这就是G
和S
字符表示ioctl名称(get和set)。
哪个操作系统?你为什么这样做? –
太多依赖外部因素提供答案 - 您可能已激活DHCP,在这种情况下,它甚至不会在您的计算机上决定它将接收哪个IP地址。 – tofro
[如何在Linux中设置C的IP地址]的可能重复(http://stackoverflow.com/questions/6652384/how-to-set-the-ip-address-from-c-in-linux) – a3f