【发布时间】:2016-06-13 22:26:53
【问题描述】:
我有一个硬代码(C 代码)来打印我的计算机 IP 地址,我会根据一些要求更改我的 IP,最后我可以在屏幕上打印更新后的 IP。现在的问题是,我需要将更改后的 IP 地址设置为我的计算机。任何人都请帮助我为使用 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
整数值 = 91
更新IP为239.192.140.168
【问题讨论】:
-
哪个操作系统?你为什么要这样做?
-
来自外部因素的依赖太多,无法提供答案 - 您可能已激活 DHCP,在这种情况下,您的计算机甚至无法决定它将接收什么 IP 地址。
-
这也可能对您有所帮助:stackoverflow.com/questions/5308090/…
-
你的例子更新的IP地址是一个多播地址,你不能把它分配给一个接口。多播地址不能是源地址,就像将一个分配给接口的情况一样。
标签: c networking network-programming ip-address