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

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

问题描述

我正在编写一个简单的网络应用程序...我需要知道我的机器在网络上的真实IP,如192.168.1.3。 getLocalHost返回127.0.0.1(在Linux上,dunno,如果它在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, dunno 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 ...如何获得REAL IP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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