HttpClient socket exception - sockets

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.

Related

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

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();
}
}
}

Hangfire MongoDB .Net Core Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1

I am using .Net Core 3.1 and Hangfire MongoDb for background scheduling, now on startup it is throwing
Autofac.Core.DependencyResolutionException: An exception was thrown while activating λ:Hangfire.IGlobalConfiguration.
---> MongoDB.Driver.MongoAuthenticationException: Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1.
---> MongoDB.Driver.MongoCommandException: Command saslStart failed: Authentication failed..
at MongoDB.Driver.Core.WireProtocol.CommandUsingQueryMessageWireProtocol`1.ProcessReply(ConnectionId connectionId, ReplyMessage`1 reply)
at MongoDB.Driver.Core.WireProtocol.CommandUsingQueryMessageWireProtocol`1.Execute(IConnection connection, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Authentication.SaslAuthenticator.Authenticate(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken
My Connection string in the config file is correct and I am able to connect to the DB from the same connection string through the Mongo Client
"ConnectionStrings": {
"MongoJobSchedulerConnection": "mongodb://user:password#ipaddress:port/DbName"
}
This is how I am adding Hangfire in Startup.cs
var mongoUrlBuilder = new MongoUrlBuilder(configuration.GetConnectionString("MongoJobSchedulerConnection"));
var mongoClient = new MongoClient(mongoUrlBuilder.ToMongoUrl());
services.AddHangfire((sp,configuration) => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseActivator<JobActivator>(new SchedulerJobActivator(sp.GetRequiredService<IServiceScopeFactory>()))
.UseMongoStorage(mongoClient, mongoUrlBuilder.DatabaseName, new MongoStorageOptions
{
MigrationOptions = new MongoMigrationOptions
{
MigrationStrategy = new MigrateMongoMigrationStrategy(),
BackupStrategy = new CollectionMongoBackupStrategy()
},
Prefix = "SchedulerQueue",
CheckConnection = true
})
);
any hint on the issue will be a great help
Thank You
The reason for this was MongoDB authentication was not happening against the admin DB somehow
This can be fixed by adding auth source to connection string like
"ConnectionStrings": {
"MongoJobSchedulerConnection": "mongodb://user:password#ipaddress:port/DbName?authSource=admin"
}
or this can be specified in MongoUrlBuilder like
var mongoUrlBuilder = new MongoUrlBuilder(configuration.GetConnectionString("MongoJobSchedulerConnection"));
mongoUrlBuilder.AuthenticationSource = "admin";

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.

Can netty establish a connect connection with an https link?

I want to complete a function with netty
http send data to netty -> netty proxy data to target https
I start a client to connet target link.
I tried proxy to http ,it's ok
But when i use https link , future.isSuccess() return false
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof FullHttpRequest) {
FullHttpRequest request = (FullHttpRequest) msg;
Bootstrap b = new Bootstrap();
b.group(ctx.channel().eventLoop())
.channel(ctx.channel().getClass())
.handler(new HttpProxyInitializer(ctx.channel()));
ChannelFuture f = b.connect("https://xxxx",443);
outboundChannel = f.channel();
f.addListener(new ChannelFutureListener() {
#Override
public void operationComplete(ChannelFuture future) {
if (future.isSuccess()) {
future.channel().writeAndFlush(msg);
} else {
ctx.channel().close();
}
}
});
}
}
So is netty connet https not feasible?
How you connect does not look correct.
You would use:
b.connect("hostname", 443)
Ensure your HttpProxyInitializer also add the SslHandler to the ChannelPipeline.
Also if things not work you should inspect the future.cause() as it will contain a Throwable which will provide details about why the operation failed.

Error while connecting to openfire server using asmack 4.0.2

Im trying to connect to Openfire Server using Asmack library 4.0.2.Im failing to get connected to the server even though i had provided correct ip address with the port.
public static final String HOST = "192.168.1.100";
public static final int PORT = 9090;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connect();
}
public void connect(){
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>(){
#Override
protected Boolean doInBackground(Void... arg0){
boolean isConnected = false;
ConnectionConfiguration config = new ConnectionConfiguration(HOST,PORT);
config.setReconnectionAllowed(true);
config.setSecurityMode(SecurityMode.disabled);
config.setDebuggerEnabled(true);
XMPPConnection connection = new XMPPTCPConnection(config);
try{
connection.connect();
Log.i("XMPPChatDemoActivity","Connected to " + connection.getHost());
isConnected = true;
} catch (IOException e){
Log.e("XMPPIOExceptionj", e.toString());
} catch (SmackException e){
Log.e("XMPPSmackException", e.toString()+" Host:"+connection.getHost()+"Port:"+connection.getPort());
} catch (XMPPException e){
Log.e("XMPPChatDemoActivity", "Failed to connect to "
+ connection.getHost());
Log.e("XMPPChatDemoActivity", e.toString());
}
return isConnected;
}
};
connectionThread.execute();
}
And im getting the following error possibly because Host and Port are getting assigned null and 0 respectively even though i had assigned them correctly.Pls help me in
sorting out this connection prob.
08-12 22:10:20.496: E/XMPPSmackException(4341):org.jivesoftware.smack.SmackException$NoResponseException Host:nullPort:0
Can you confirm that port 9090 is the correct port for XMPP protocol? Default install of Openfire will set port 9090 to be used for accessing the HTTP based configuration console. I recommend you try connecting to the port for XMPP connections as specified on the main index page of the Openfire configuration console (Listed below "Server Ports").
The following is taken from the Openfire configuration console:
5222 The standard port for clients to connect to the server. Connections may or may not be encrypted. You can update the security settings for this port.
I think your Host adress is wrong too, you must use the adress to connect openfire server. It must be "127.0.0.1" or just write "localhost". and the port is 5222 to be able to talk from client to server.