如何使用C程序设置计算机的IP地址?

如何使用C程序设置计算机的IP地址?,c,networking,network-programming,ip-address,C,Networking,Network Programming,Ip Address,我有一个硬代码(C代码)来打印我的计算机IP地址,我会根据一些要求更改我的IP,最后我可以在屏幕上打印更新的IP。现在的问题是,我需要为我的计算机设置更改后的IP地址。任何人请帮助我设置一个新的IP地址到一台使用C语言作为平台的计算机。 我的硬代码及其输出附在下面 #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #includ

我有一个硬代码(C代码)来打印我的计算机IP地址,我会根据一些要求更改我的IP,最后我可以在屏幕上打印更新的IP。现在的问题是,我需要为我的计算机设置更改后的IP地址。任何人请帮助我设置一个新的IP地址到一台使用C语言作为平台的计算机。 我的硬代码及其输出附在下面

#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;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
int main()
{
int n,chain=2,ADU=2,cam_port=2,IP=0,公式,stream_num=3;
结构ifreq-ifr;
字符数组[]=“eth0”;
int_val=0;
int c=0;
char*some_addr;
n=插座(AF INET,插座DGRAM,0);
ifr.ifr\u addr.sa\u family=AF\u INET;
strncpy(ifr.ifr_名称、数组、IFNAMSIZ-1);
ioctl(n、SIOCGIFADDR和ifr);
关闭(n);
printf(“IP地址是%s-%s\n”、数组、inet\u ntoa(((struct sockaddr\u in*)和ifr.ifr\u addr)->sin\u addr));
some\u addr=inet\u ntoa(((struct sockaddr\u in*)&ifr.ifr\u addr)->sin\u addr);
printf(“最后一个字符八位组是%c%c%c\n”,一些地址[11],一些地址[12],一些地址[13]);
对于(c=11;某些地址[c]!='\0';c++)
{
int_val=int_val*10+some_addr[c]-“0”;
}
printf(“int value=%d\n”,int_val);
IP=整数;
公式=(链-1)*128)+(ADU-1)*32)+(cam_端口-1)*4)+(流数+1);
IP=公式;
printf(“更新的IP为239.192.140.%d\n”,IP);
返回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地址。这可能会对您有所帮助:例如,更新的IP地址是一个多播地址,一个d不允许将其分配给接口。多播地址不能是源地址,将一个地址分配给接口就是这种情况。