---
title: "InetAddress.getLocalHost().getHostAddress()获取的IP不正确"
author: "chainhou"
date: "2013-06-09T17:43:40Z"
tags: []
categories: ["编程语言"]
slug: "inetaddress-getlocalhost-gethostaddress-ip"
draft: false
lastmod: "2013-06-09T17:43:40Z"
id: 1885029
url: "https://chainhou.iteye.com/blog/1885029"
---

今天把在Windows下运行很正常的程序拿到Linux下测试，却出现了问题，经过检查发现是InetAddress.getLocalHost().getHostAddress() 取本地IP地址时出现了问题。因为期望得到的IP是222.xxx.xxx.xx，但实际打印出来的IP地址却是127.0.0.1。

查看 /etc/hosts 文件，里面有一条本机名和 222.xxx.xxx.xx这个 IP 对应的记录。把它注释掉，然后修改本机的主机名，又在 hosts 文件中加入主机名和222. xx.xx.xx的对应，问题解决了。

通过问题的解决方法，我们可以发现InetAddress.getLocalHost().getHostAddress() 方法找到本机 IP的实现方法——依靠本机的机器名去查询IP 地址，和 ping `hostname` 返回的 IP 地址是同一个，并不是 ipconfig 方法得到的 eth0 IP 地址。

getHostAddress() ：返回类型是String，返回 IP 地址字符串（以文本表现形式）。

getLocalHost()：返回类型是static InetAddress，返回本地主机