MailKit - smtp.Connect throw exception in C# .Net - mailkit

Exception while connecting to the server: A connection attempt failed because the connected party did not properly respond after a period of time, or an established connection failed because the connected host has failed to respond.
1.) able to ping the server
2.) telnet smtp.office365.com 587 respond as expected.
public ConnectSmtpServer()
{
using MailKit.Net.Smtp;
string _SmtpServer = "smtp.office365.com";
int _portNumber = 587;
Console.WriteLine("Welcome!");
using (SmtpClient smtp = new SmtpClient())
{
try
{
smtp.Timeout = 30 * 1000;
smtp.Connect(_SmtpServer, _portNumber, SecureSocketOptions.Auto);
Console.WriteLine("Test smtp connection using MailKit.Net !");
smtp.Connect(_SmtpServer, _portNumber, SecureSocketOptions.Auto);
Console.WriteLine();
}
}
}

Related

HttpClient socket exception

I am trying to call some external API hosted on azure from my web Api. The API is working fine on my local machine but when I deploy it IIS on server it starts throwing System.Net.Sockets.SocketException (10060).A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. Although I have increased the request timeout to 5 minutes but connection is silently stopping after 21 seconds and throwing aforementioned exception.
Here is my code:
var telemetries = new TelemetryResponse();
var client = httpClientFactory.CreateClient("Lynx");
client.Timeout = TimeSpan.FromMinutes(5);
var httpResponseMessage = await client.GetAsync("vehicletelemetries/All?key=iLJIbAVXOnpKz5xyF0zV44yepu5OVfmZFhkHM7x");
if (httpResponseMessage.IsSuccessStatusCode)
{
string content = await httpResponseMessage.Content.ReadAsStringAsync();
telemetries = JsonConvert.DeserializeObject<TelemetryResponse>(content);
}
Exception I am getting is:
System.Net.Sockets.SocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
at System.Net.Sockets.Socket.g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
You got an error code:
WSAETIMEDOUT
10060
Connection timed out.
A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond.
https://learn.microsoft.com/en-us/windows/win32/winsock/windows-sockets-error-codes-2#WSAETIMEDOUT
Check your network connection, ip adress, port and maybe the connection got blocked from a firewall.
Hi guys the culprit was the proxy and we have to configure our HttpClient with proxy while creating it/registering in the DI container. I have registered the HttpClient in DI like this.
var proxySettings = new ProxySetting();
Configuration.Bind(nameof(ProxySetting), proxySettings);
services.AddHttpClient("Lynx", client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("LynxUrl").Value);
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { Proxy = new MyProxy(proxySettings)});
And my proxy code is
public class MyProxy : IWebProxy
{
private readonly ProxySetting _proxySetting;
public MyProxy(ProxySetting proxySetting)
{
_proxySetting = proxySetting;
}
public ICredentials Credentials
{
//get { return new NetworkCredential("username", "password"); }
get { return new NetworkCredential(_proxySetting.UserName, _proxySetting.Password,_proxySetting.Domain); }
set { }
}
public Uri GetProxy(Uri destination)
{
return new Uri(_proxySetting.ProxyUrl);
}
public bool IsBypassed(Uri host)
{
return false;
}
}
It has resolved my problem completely.

NetCore IPV6 socket connection fails on linux-arm

I am trying to establish an IPV6 socket connection with net-core 3.0 on a linux-arm platform (raspberry pi).
At the time when I try to bind the socket to the local ethernet adapter an Exception ((22): Invalid argument [fe80::211c:bf90:fbbf:9800]:5400) is thrown.
When i try the same on my windows development machine (with a different link-local ip), everything works fine.
IPV4 socket connection is also possible on both, my windows development machine and on the target linux-arm platform.
To the source code:
I used the socket example of microsoft as a base and changed the IPV4 into an IPV6 address.
The exception is thrown after the "Bind" method.
Here is the client side code:
//definet the target endpoint
IPAddress ipAddress;
IPAddress.TryParse("fe80::211c:bf90:fbbf:9800", out ipAddress);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 5400);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily ,SocketType.Stream, ProtocolType.Tcp);
//bind to the local network interface
IPAddress localIp;
IPAddress.TryParse("fe80::833:e68b:32ee:4c39", out localIp);
EndPoint localEndPoint = new IPEndPoint(IPAddress.IPv6Any, 0);
sender.Bind(localEndPoint);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
The input of Ron was in fact the missing part. Hence the target endpoint IpAddress has to provided with the ScopeId (NIC Nr).
//definet the target endpoint
IPAddress ipAddress;
IPAddress.TryParse("fe80::211c:bf90:fbbf:9800", out ipAddress);
ipAddress.ScopeId = scopeId;
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 5400);
To the scope ID of the first link local address for example this code can be used:
private static long GetScopeIdForHostLinkLocal()
{
IPAddress firstLinkLocal = null;
var info = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nic in info)
{
var ipProps = nic.GetIPProperties();
var uniAddresses = ipProps.UnicastAddresses;
foreach (UnicastIPAddressInformation addressInfo in uniAddresses)
{
if (addressInfo.Address.IsIPv6LinkLocal)
{
firstLinkLocal = addressInfo.Address;
break;
}
}
if (firstLinkLocal != null)
{
break;
}
}
if (firstLinkLocal != null)
{
return firstLinkLocal.ScopeId;
}
else
{
return -1;
}
}

Not able to connet to ejabberd server through smack

I am setting up a chat service using ejabberd and building an XMPP client for android devices using smack.
Here are some important details.
server OS: ubuntu 18.04
server hosted as localhost (jid format: alice#localhost).
server system IP : 192.168.4.162
Client:
Smack 4.3.1
Using external phone through USB debugging : Nokia 3.1 Plus.
Here is my code
Here are some of the configurations I tried.
private class MyLoginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
// Create a connection to the jabber.org server.
InetAddress addr = null;
try{
addr = InetAddress.getByName("192.168.4.162");
}catch(UnknownHostException e){
e.printStackTrace();
}
XMPPTCPConnectionConfiguration config = null;
DomainBareJid serviceName = null;
try{
serviceName = JidCreate.domainBareFrom("localhost");
System.out.println("serviceName: "+serviceName);
}catch(XmppStringprepException e){
e.printStackTrace();
}
HostnameVerifier verifier = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// ConnectionConfiguration connConfig = new ConnectionConfiguration("talk.google.com", PORT, SERVICE);
try{
config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("alice", "9009")
.setHost("192.168.4.162")
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setXmppDomain("localhost")
.setHostnameVerifier(verifier)
.setHostAddress(addr)
.setPort(5222)
.build();
}catch(XmppStringprepException e){
e.printStackTrace();
}
AbstractXMPPConnection conn1 = new XMPPTCPConnection(config);
try {
System.out.println("Connecting......."); AndroidUsingLinkProperties.setup(getApplicationContext());
conn1.connect().login();
if(conn1.isConnected()) {
Log.w("app", "conn done");
}
conn1.login();
if(conn1.isAuthenticated()) {
Log.w("app", "Auth done");
}
}
catch (Exception e) {
Log.w("app", e.toString());
}
return "";
}
#Override
protected void onPostExecute(String result) {
}
}
The configurations i tried above the result is:
org.jivesoftware.smack.SmackException$ConnectionException: The following addresses failed: '192.168.4.162:5222' failed because: /192.168.4.162 exception: java.net.ConnectException: failed to connect to /192.168.4.162 (port 5222) from /192.168.4.182 (port 39568) after 30000ms: isConnected failed: EHOSTUNREACH (No route to host)
however I am successfully able to build a connection to my server through any other client(psi, gajim, My web app(BOSH connection)).
following may help if networking is the issue:
$ nmap localhost
Starting Nmap 7.80 ( https://nmap.org ) at 2019-08-28 18:00 IST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000056s latency).
Not shown: 992 closed ports
PORT STATE SERVICE
111/tcp open rpcbind
139/tcp open netbios-ssn
445/tcp open microsoft-ds
631/tcp open ipp
5222/tcp open xmpp-client
5269/tcp open xmpp-server
5280/tcp open xmpp-bosh
8600/tcp open asterix
Nmap done: 1 IP address (1 host up) scanned in 0.09 seconds
I have been there and I found out the accidentally my phone and my ejabberd server were on different network. They should be on the same network as in this case. Make sure you are on same network and this error should go away.

CFSocket created in Swift not listening

I'm trying to get basic Bonjour discovery up and running using the sample code from a 2012 WWDC session, but having converted it to Swift. It's partially working. I am able to register a port, and register my service on that port. The client is able to discover that service, and resolve it.
Here's the issue: I call CFSocketCreateWithNative() and specify the callback listener, but that callback never gets called. Further, I tried connecting wiht telnet (telnet localhost 12345) and I get:
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
Trying fe80::1...
telnet: connect to address fe80::1: Connection refused
telnet: Unable to connect to remote host
This is an abbreviated version of how I'm registering the sockets, with the full Swift file in a Gist:
private func registerIPv4Socket() throws -> (Int32, in_port_t) {
let fd4 = socket(AF_INET, SOCK_STREAM, 0)
var sin = sockaddr_in()
sin.sin_family = sa_family_t(AF_INET)
sin.sin_len = UInt8(sizeofValue(sin))
sin.sin_port = 0
withUnsafePointer(&sin) {
Foundation.bind(fd4, UnsafePointer($0), UInt32(sin.sin_len))
}
var addrLen = socklen_t(sizeofValue(sin))
withUnsafeMutablePointers(&sin, &addrLen) { (sinPtr, addrPtr) -> Int32 in
getsockname(fd4, UnsafeMutablePointer(sinPtr), UnsafeMutablePointer(addrPtr))
}
let listenError = listen(fd4, 5)
return (fd4, sin.sin_port)
}
private func registerIPv6Socket(port: in_port_t) throws -> Int32 {
let fd6 = socket(AF_INET6, SOCK_STREAM, 0)
var one: Int32 = 1
withUnsafePointer(&one) {
setsockopt(fd6, IPPROTO_IPV6, IPV6_V6ONLY, UnsafePointer($0), socklen_t(sizeofValue(one)))
}
var sin6 = sockaddr_in6()
sin6.sin6_family = sa_family_t(AF_INET6)
sin6.sin6_len = UInt8(sizeofValue(sin6))
sin6.sin6_port = port
withUnsafePointer(&sin6) {
Foundation.bind(fd6, UnsafePointer($0), UInt32(sin6.sin6_len))
}
var addrLen = socklen_t(sizeofValue(sin6))
withUnsafeMutablePointers(&sin6, &addrLen) { (sinPtr, addrPtr) -> Int32 in
getsockname(fd6, UnsafeMutablePointer(sinPtr), UnsafeMutablePointer(addrPtr))
}
listen(fd6, 5)
return fd6
}
Why isn't my app listening on the port it's reporting it should be?
Your IPv4 socket is listening on port sin.sin_port.bigEndian, but your IPv6 socket is listening on the little endian port. Update your IPv6 code to use the big endian port:
sin.sin6_port = port.bigEndian

RMI and 2 machines - two way communication

I've got problem with RMI comunication between 2 machines (win 7 and win xp VM). The exception with I have problem is:
java.rmi.ConnectException: Connection refused to host: 169.254.161.21; nested exception is:
java.net.ConnectException: Connection timed out: connect
It's really weired because during connection I use address 192.168.1.4 (server), but exception somehow show sth different. I disabled firewall on both side. Ping working to both side. I tried telnet to server and use server port:
telnet 192.168.1.4 1099 and it's working... I can't figure out where the problem is.
If I run this on host side (eg server side) everything works fine.
How is it look from SERVER:
public class Server
{
public static void main(String args[])
{
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
String portNum, registryURL;
try{
System.out.println("Enter the RMIregistry port number:");
portNum = (br.readLine()).trim();
int RMIPortNum = Integer.parseInt(portNum);
startRegistry(RMIPortNum); // Registry registry = LocateRegistry.createRegistry(RMIPortNum);
ServerSide_Impl exportedObj = new ServerSide_Impl();
registryURL = "rmi://localhost:" + portNum + "/callback";
//registryURL = "rmi://192.168.1.4:" + portNum + "/callback";
Naming.rebind(registryURL, exportedObj);
System.out.println("Callback Server ready.");
}// end try
catch (Exception re) {
System.out.println(
"Exception in HelloServer.main: " + re);
} // end catch
} // end main
//This method starts a RMI registry on the local host, if
//it does not already exists at the specified port number.
private static void startRegistry(int RMIPortNum) throws RemoteException
{
try
{
Registry registry = LocateRegistry.getRegistry(RMIPortNum);
registry.list( );
// This call will throw an exception
// if the registry does not already exist
}
catch (RemoteException e)
{
Registry registry = LocateRegistry.createRegistry(RMIPortNum);
}
} // end startRegistry
} // end class
Client side is look like:
try
{
this.serverAd = serverAddress.getText();
String path = System.getProperty("user.dir");
String pathAfter = path.replace("\\", "/");
String pathFile = "file:/"+pathAfter + "/wideopen.policy";
System.setProperty("java.security.policy", pathFile);
System.setSecurityManager(new RMISecurityManager());
this.hostName = hostNameTextField.getText();
this.portNum = hostPortNumberTextField.getText();
RMIPort = Integer.parseInt(this.portNum);
this.time = Integer.parseInt(timeTextField.getText());
//this.registryURL = "rmi://localhost:" + this.portNum + "/callback";
String registryURLString = "rmi://"+this.serverAd+":" + this.portNum + "/callback";
this.registryURL = registryURLString;
ConsoleTextField.append("\n"+ this.registryURL + "\n");
// find the remote object and cast it to an
// interface object
obj = (ServerSide_Interface)Naming.lookup(this.registryURL);
boolean test = obj.Connect();
if(test)
{
callbackObj = new ClientSide_Impl();
// register for callback
obj.registerForCallback(callbackObj);
isConnected = true;
ConsoleTextField.append("Nawiązano połaczenie z serwerem\n");
TableModel modelTemp = obj.Server_GenerateStartValues();
myDataTable.setModel(modelTemp);
myDataTable.setEnabled(true);
}
else ConsoleTextField.append("Brak połączenia z serwerem\n");
}
catch (Exception ex ){
ConsoleTextField.append(ex + "\n");
System.out.println(ex);
}
This connection is working fine if I run client on host side. If I use VM and try connect between 2 different machines, I can;t figure out what did I do bad
There is something wrong with your etc/hosts file or your DNS setup. It is providing the wrong IP address to the server as the server's external IP address, so RMI embeds the wrong address into the stub, so the client attempts to connect to the wrong IP address.
If you can't fix that, you can set the system property java.rmi.server.hostname to the correct IP address at the server JVM, before exporting any RMI objects (including Registries). That tells RMI to embed that address in the stub.