Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added local binding ip option #247

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions MailKit/Net/Smtp/SmtpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,19 @@ public SmtpClient (IProtocolLogger protocolLogger) : base (protocolLogger)
}
}

/// <summary>
/// Set the local IP address to bind.
/// </summary>
/// <remarks>
/// Set the IP address the socket will use to bind a specific local IP address configured on the computer.
/// </remarks>
/// <value>The local IP address to use. Null for any.</value>
public string LocalIpBinding
{
set;
private get;
}

/// <summary>
/// Gets or sets the local domain.
/// </summary>
Expand Down Expand Up @@ -780,6 +793,26 @@ public override void Connect (string host, int port = 0, SecureSocketOptions opt
for (int i = 0; i < ipAddresses.Length; i++) {
socket = new Socket (ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);

if (LocalIpBinding != null) {

IPAddress bindIP;
if (IPAddress.TryParse(LocalIpBinding, out bindIP))
{
//Create an endpoint for the specified IP on any port
IPEndPoint bindEndPoint = new IPEndPoint(bindIP, 0);

//Bind the socket to the endpoint
try
{
socket.Bind(bindEndPoint);
}catch(SocketException ex){
throw new Exception("Can't bind to IP " + bindEndPoint.Address, ex);
}
}
else
throw new Exception("Can't bind to IP " + LocalIpBinding);
}

try {
cancellationToken.ThrowIfCancellationRequested ();
socket.Connect (ipAddresses[i], port);
Expand Down