1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.address;
17
18 import io.netty.channel.ChannelFuture;
19 import io.netty.channel.ChannelFutureListener;
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.channel.ChannelOutboundHandler;
22 import io.netty.channel.ChannelOutboundHandlerAdapter;
23 import io.netty.channel.ChannelPromise;
24
25 import java.net.NetworkInterface;
26 import java.net.SocketAddress;
27
28
29
30
31
32
33
34
35 public abstract class DynamicAddressConnectHandler extends ChannelOutboundHandlerAdapter {
36
37 @Override
38 public final void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress,
39 SocketAddress localAddress, ChannelPromise promise) {
40 final SocketAddress remote;
41 final SocketAddress local;
42 try {
43 remote = remoteAddress(remoteAddress, localAddress);
44 local = localAddress(remoteAddress, localAddress);
45 } catch (Exception e) {
46 promise.setFailure(e);
47 return;
48 }
49 ctx.connect(remote, local, promise).addListener(new ChannelFutureListener() {
50 @Override
51 public void operationComplete(ChannelFuture future) {
52 if (future.isSuccess()) {
53
54
55 future.channel().pipeline().remove(DynamicAddressConnectHandler.this);
56 }
57 }
58 });
59 }
60
61
62
63
64
65
66
67 protected SocketAddress localAddress(
68 @SuppressWarnings("unused") SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
69 return localAddress;
70 }
71
72
73
74
75
76
77
78 protected SocketAddress remoteAddress(
79 SocketAddress remoteAddress, @SuppressWarnings("unused") SocketAddress localAddress) throws Exception {
80 return remoteAddress;
81 }
82 }