简体   繁体   English

从Java HTTP服务器获取全局IP地址

[英]Get global IP address from java http server

I m starting a local http server using this code: 我正在使用以下代码启动本地http服务器:

    HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
    server.createContext("/intro", new MyHandler());
    server.setExecutor(null);
    server.start();

now I want to hit the url /intro from some other server.The problem is I don't know the ip adress to hit.Doing server.getAddress() gives 0.0.0.0:8000 .I want to find the global ip address. 现在我想从其他服务器上访问url /intro 。问题是我不知道要打的IP地址server.getAddress()给出0.0.0.0:8000 。我想找到全局ip地址。

You have to know what is your ip (cmd and ipconfig) and get IPv4 address. 您必须知道什么是IP(cmd和ipconfig)并获取IPv4地址。 But remember that is only your local IP visible in your local network, so only users in the same network can see it. 但是请记住,只有本地IP在本地网络中可见,因此只有同一网络中的用户才能看到它。 In global network you are identified by your internet provider IP. 在全球网络中,您通过互联网提供商IP进行标识。

InetSocketAddress(int port) InetSocketAddress(INT端口)

Creates a socket address where the IP address is the wildcard address and the port number a specified value. 创建一个套接字地址,其中IP地址为通配符地址,端口号为指定值。

InetSocketAddress(InetAddress addr, int port) InetSocketAddress(InetAddress地址,int端口)

Creates a socket address from an IP address and a port number. 根据IP地址和端口号创建套接字地址。

The wildcard is a special local IP address. 通配符是一个特殊的本地IP地址。 It usually means "any" and can only be used for bind operations.The value of this IP address is 0.0.0.0. 通常表示“任何”,并且只能用于绑定操作。此IP地址的值为0.0.0.0。

so use another constructor of InetSocketAddress when you can put hostname 因此,当您可以放置​​主机名时,请使用InetSocketAddress的另一个构造函数

new InetSocketAddress(String hostname, int port) calls InetAddress.getByName(hostname). 新的InetSocketAddress(字符串主机名,int端口)调用InetAddress.getByName(主机名)。

Now you shall get your local ip address when you query server.getAddress() 现在,当您查询server.getAddress()时,您将获得本地IP地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM