java InetAddress.getLocalHost();返回 127.0.0.1 ... 如何获得真实 IP? [英] java InetAddress.getLocalHost(); returns 127.0.0.1 ... how to get REAL IP?

查看:39
本文介绍了java InetAddress.getLocalHost();返回 127.0.0.1 ... 如何获得真实 IP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的网络应用程序.我需要知道我的机器在网络上的真实 IP,比如 192.168.1.3 .getLocalHost 返回 127.0.0.1(在 Linux 上,我不知道在 Windows 上是否相同).怎么做?

I'm writing a simple networking app. I need to know the real IP of my machine on the network, like 192.168.1.3 . getLocalHost returns 127.0.0.1 (on Linux, I don't know if it is the same on windows). How to do it?

推荐答案

如果您确实想使用机器上的所有 IP 地址,您可以通过 NetworkInterface 类获得这些地址.当然,然后您需要真正想要使用哪个,但这取决于您使用它的目的,或者您可能需要扩展您使用它的方式来解释多个地址.

If you actually want to work with all of the IP addresses on the machine you can get those with the NetworkInterface class. Of course, then you need to which one you actually want to use, but that's going to be different depending on what you're using it for, or you might need to expand the way you're using it to account for multiple addresses.

import java.net.*;
import java.util.*;

public class ShowInterfaces
{
        public static void main(String[] args) throws Exception
        {
                System.out.println("Host addr: " + InetAddress.getLocalHost().getHostAddress());  // often returns "127.0.0.1"
                Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
                for (; n.hasMoreElements();)
                {
                        NetworkInterface e = n.nextElement();
                        System.out.println("Interface: " + e.getName());
                        Enumeration<InetAddress> a = e.getInetAddresses();
                        for (; a.hasMoreElements();)
                        {
                                InetAddress addr = a.nextElement();
                                System.out.println("  " + addr.getHostAddress());
                        }
                }
        }
}

这篇关于java InetAddress.getLocalHost();返回 127.0.0.1 ... 如何获得真实 IP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆