一台机器上,配置了多个IP,有多个应用,他们要使用相同的端口,这样能实现吗?
比如,IIS和tomcat并行运行,没有任何集成,他们分别侦听各自的IP,都是80端口,这样可行吗?
我用java做了本地的测试,机器上给一个网卡配置了2个ip
192.168.1.176
192.168.1.177
然后运行下面的程序
- import java.io.IOException;
- import java.io.OutputStream;
- import java.net.InetSocketAddress;
- import com.sun.net.httpserver.HttpExchange;
- import com.sun.net.httpserver.HttpHandler;
- import com.sun.net.httpserver.HttpServer;
- import com.sun.net.httpserver.spi.HttpServerProvider;
- /**
- * 测试一台机器多个IP,相同端口的服务侦听
- *
- * @author 老紫竹(Java世纪网,java2000.net)
- */
- public class Test {
- public static void main(String[] args) throws Exception {
- new HTTPServerTest("192.168.1.176", 60080);
- new HTTPServerTest("192.168.1.177", 60080);
- }
- }
- class HTTPServerTest {
- private String ip;
- private int port;
- HTTPServerTest(String ip, int port) throws IOException {
- this.ip = ip;
- this.port = port;
- HttpServerProvider httpServerProvider = HttpServerProvider.provider();
- // 绑定端口
- InetSocketAddress addr = new InetSocketAddress(ip, port);
- HttpServer httpServer = httpServerProvider.createHttpServer(addr, 1);
- httpServer.createContext("/", new HTTPDownloaderServiceHandler());
- httpServer.setExecutor(null);
- httpServer.start();
- System.out.println("started");
- }
- class HTTPDownloaderServiceHandler implements HttpHandler {
- public void handle(HttpExchange httpExchange) {
- try {
- String response = "OK!" + ip + ":" + port;
- httpExchange.sendResponseHeaders(200, response.getBytes().length);
- OutputStream out = httpExchange.getResponseBody();
- out.write(response.getBytes());
- out.close();
- httpExchange.close();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }
- }
启动后,分别在浏览器输入
http://192.168.1.176:60080
显示
OK!192.168.1.176:60080输入
http://192.168.1.177:60080
显示
OK!192.168.1.177:60080
结论:一台机器上的端口等于机器的ip数量*65536,也就是每个ip都有自己的一组独立端口。
但可惜,我没有在tomcat里面配置出2个同时侦听8080的服务出来,她的service.xml里面
<Server port="8005" shutdown="SHUTDOWN">
这个只有端口,没有host的配置。希望知道如何配置的朋友给我留言。谢谢。
如果我自己找到了,也会再单独发上来的。