Home > Software design >  Use two local ips in same port
Use two local ips in same port

Time:11-11

it is possible in local to use two local ips (127.0.0.1, 127.0.0.2) apart from use /etc/host to create alias?

I'm trying to test two services that point to same port.

I was trying to use NettyServerBuilder with InetSocketAddress in ip 127.0.0.2 but it's not possible and return a Caused by: java.net.BindException: Address already in use: bind

final SocketAddress socketAddress = new InetSocketAddress("127.0.0.2", 8888);

Server server = NettyServerBuilder.forAddress(socketAddress)
    .addService(coordinator)
    .build();
server.start();

final SocketAddress socketAddress2 = new InetSocketAddress("127.0.0.1", 8888);

Server server2 = NettyServerBuilder.forAddress(socketAddress2)
    .addService(coordinator)
    .build();
server2.start();

CodePudding user response:

As you can read on https://en.wikipedia.org/wiki/Localhost,

IPv4 network standards reserve the entire 127.0.0.0/8 address block for loopback purposes. That means any packet sent to one of those 16,777,214 addresses (127.0.0.1 through 127.255.255.254) is looped back. IPv6 has just a single address, ::1.

So you cannot use the same port number for two loopback addresses unless you change DNS resolution editing /etc/hosts.

CodePudding user response:

Each port has a single, so if you have run your program it will throw an error, but if run two instances then use diffrent available port.

final SocketAddress socketAddress = new InetSocketAddress("127.0.0.2", 8888);

Server server = NettyServerBuilder.forAddress(socketAddress)
    .addService(coordinator)
    .build();
server.start();

final SocketAddress socketAddress2 = new InetSocketAddress("127.0.0.1", [Available_Port]);

Server server2 = NettyServerBuilder.forAddress(socketAddress2)
    .addService(coordinator)
    .build();
server2.start();
  • Related