From 30588f7be0e97730ddc986a5745e6866c9bf8bd1 Mon Sep 17 00:00:00 2001 From: VADemon Date: Mon, 21 Dec 2020 15:58:02 +0100 Subject: [PATCH] Add local address binding to Client --- .../github/steveice10/packetlib/Client.java | 30 +++++++++++++++++-- .../packetlib/tcp/TcpClientSession.java | 1 + 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/steveice10/packetlib/Client.java b/src/main/java/com/github/steveice10/packetlib/Client.java index 0757196a..35a4256d 100644 --- a/src/main/java/com/github/steveice10/packetlib/Client.java +++ b/src/main/java/com/github/steveice10/packetlib/Client.java @@ -8,15 +8,23 @@ import com.github.steveice10.packetlib.packet.PacketProtocol; public class Client { private String host; private int port; + private String bindAddress; + private int bindPort; private PacketProtocol protocol; private Session session; - public Client(String host, int port, PacketProtocol protocol, SessionFactory factory) { + public Client(String host, int port, String bindAddress, int bindPort, PacketProtocol protocol, SessionFactory factory) { this.host = host; this.port = port; + this.bindAddress = bindAddress; + this.bindPort = bindPort; this.protocol = protocol; this.session = factory.createClientSession(this); } + + public Client(String host, int port, PacketProtocol protocol, SessionFactory factory) { + new Client(host, port, null, 0, protocol, factory); + } /** * Gets the host the client is connecting to. @@ -35,7 +43,25 @@ public class Client { public int getPort() { return this.port; } - + + /** + * Gets the the local address the client is connecting from. + * + * @return Client's local IP address or null if default. + */ + public String getBindAddress() { + return this.bindAddress; + } + + /** + * Gets the the local port the client is connecting from. + * + * @return Client's local port or 0 if default. + */ + public int getBindPort() { + return this.bindPort; + } + /** * Gets the packet protocol of the client. * diff --git a/src/main/java/com/github/steveice10/packetlib/tcp/TcpClientSession.java b/src/main/java/com/github/steveice10/packetlib/tcp/TcpClientSession.java index 4607184d..d6ef23a3 100644 --- a/src/main/java/com/github/steveice10/packetlib/tcp/TcpClientSession.java +++ b/src/main/java/com/github/steveice10/packetlib/tcp/TcpClientSession.java @@ -142,6 +142,7 @@ public class TcpClientSession extends TcpSession { try { InetSocketAddress remoteAddress = resolveAddress(); bootstrap.remoteAddress(remoteAddress); + bootstrap.localAddress(client.getBindAddress(), client.getBindPort()); ChannelFuture future = bootstrap.connect().sync(); if(future.isSuccess()) {