首页 > 其他分享 >多IP情况下如何获取本地的第一个IP及如何调整本地的第一个IP

多IP情况下如何获取本地的第一个IP及如何调整本地的第一个IP

时间:2023-01-17 13:35:17浏览次数:32  
标签:网段 第一个 IP hostname etc hosts 本地 include

昨天交付的同事联系我,相同的业务,但线上系统中,OPTIONS消息的Via地址是20网段的,但测试系统中的Via地址是181网段的。他说感到非常的奇怪。

我分析了业务的代码,OPTIONS中的Via中的用的是采用gethostbyname获取的。这意味着该函数获取的系统的默认的第一个IP。如果操作系统有多个IP,如何设置它们的优先级呢?

我先是意多IP的顺序是ifconfig中看到的顺序。但经过现场检查线上系统的IP网段顺序是相同的,先181网段后20网段。

今天灵感到来,/etc/hosts中配置了多IP及主机名字的对应关系,第一个IP是不是就在/etc/hosts中配置的呢?

于是我先写了获取IP的代码,具体如下:

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <dirent.h>

int main()
{
  char hostname[100]={0};
  char localIpAddress[256]={0};
  struct hostent *h;
  gethostname(hostname,sizeof(hostname));
  printf("host name is %s \n",hostname);
  h=gethostbyname(hostname);
  struct in_addr *temp;
  temp=(struct in_addr *)h->h_addr;
  strcpy(localIpAddress,inet_ntoa(*temp));
  printf("first ip is %s\n",localIpAddress);
}

我将这段代码保存文件getfirstipbyhostname.c.g++编译

g++ getfistipbyhostname.c -o getfstip

我先运行下:

多IP情况下如何获取本地的第一个IP及如何调整本地的第一个IP_gethostbyname

我查看下/etc/hsots中的顺序

多IP情况下如何获取本地的第一个IP及如何调整本地的第一个IP_gethostbyname_02

然后我调整下/etc/hosts中的IP的顺序:

多IP情况下如何获取本地的第一个IP及如何调整本地的第一个IP_inet_ntoa_03

多IP情况下如何获取本地的第一个IP及如何调整本地的第一个IP_inet_ntoa_04

由此可见获取本机的第一个IP地址,取决于/etc/hosts中配置的顺序。

 

 

 

 

标签:网段,第一个,IP,hostname,etc,hosts,本地,include
From: https://blog.51cto.com/u_15942605/6017172

相关文章