SNMPsharpnet SnmpNetworkException: 'Network error: connection reset by peer.' - connection

I am beginner in C# and I am trying to create a tool to read snmp OID for some of my devices.
In general the system is working fine at the exception of when I cannot reach the IP address or when the IP Address is not using the same OID.
What I would like to achieve is : In case the device is not reachable : skip to the next one . In case the device has not the right OID : skip to the next one.
Currently when it happens I have an error like this one :
Error
SnmpSharpNet.SnmpNetworkException: 'Network error: connection reset by peer.'
Caused by
SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
Sample of my code
//Start
UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
Pdu pdu = new Pdu(PduType.Get);
pdu.VbList.Add(".1.3.6.1.4.1.1552.21.3.1.1.5.1.0");
pdu.VbList.Add(".1.3.6.1.4.1.1552.21.3.1.1.5.2.0");
pdu.VbList.Add(".1.3.6.1.4.1.1552.21.3.1.1.5.7.0");
pdu.VbList.Add(".1.3.6.1.4.1.1552.21.3.1.1.5.8.0");
// Make SNMP request
SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
// If result is null then agent didn't reply or we couldn't parse the reply.
if (result != null)
{
if (result.Pdu.ErrorStatus != 0)
{
// agent reported an error with the request
MessageBox.Show("Error");
}
Thank you for your help

I have faced the same issue and the solution was to install SNMP Service on your windows and it should start working fine
this link should help you https://support.microsoft.com/en-us/help/324263/how-to-configure-the-simple-network-management-protocol-snmp-service-i

Related

How can I make a TLS connection using Vala?

I'm trying to figure out how can I make a proper TLS connection using Gio. The Gio documentation says you can create a TLS connection just by setting the tls flag on the SocketClient. Below is a Gio networking sample from the gnome wiki. When I set the tls flag, the TLS layer is configured automatically but validating the certificates fails unless I skip the validation.
Do I have to validate certificates myself or is GLib supposed to do the validation? Can somebody provide a full example on how to use TLS in Vala?
var host = "developer.gnome.org";
try {
// Resolve hostname to IP address
var resolver = Resolver.get_default ();
var addresses = resolver.lookup_by_name (host, null);
var address = addresses.nth_data (0);
print (#"Resolved $host to $address\n");
// Connect
var client = new SocketClient ();
client.set_tls(true);
// skips certificate validation
client.set_tls_validation_flags( 0 );
var conn = client.connect (new InetSocketAddress (address, 443));
print (#"Connected to $host\n");
// Send HTTP GET request
var message = #"GET / HTTP/1.1\r\nHost: $host\r\n\r\n";
conn.output_stream.write (message.data);
print ("Wrote request\n");
// Receive response
var response = new DataInputStream (conn.input_stream);
var status_line = response.read_line (null).strip ();
print ("Received status line: %s\n", status_line);
} catch (Error e) {
stderr.printf ("%s\n", e.message);
}
And another thing I want to ask is; when I run the code above I get this output:
Resolved developer.gnome.org to 8.43.85.14
Connected to developer.gnome.org
Wrote request
Received status line: HTTP/1.1 200 OK
But when I try to connect 'developer.mozilla.org', I'm getting the following error:
Resolved developer.mozilla.org to 54.192.235.2
Error performing TLS handshake: A packet with illegal or unsupported version was received.
Can anybody tell me the reason why I am getting this error? (By the way the version of GLib installed on my system is 2.64.6)
What you're doing so far is mostly correct, but you will probably want to do a little bit more to handle potential certificate errors during the TLS handshaking (see below).
Do I have to validate certificates myself or is GLib supposed to do the validation?
Note that SocketClient.set_tls_validation_flags is deprecated. To handle validation errors you can connect to the accept_certificate signal on the TlsClientConnection prior to handshaking:
var client = new SocketClient ();
client.set_tls(true);
client.event.connect ((SocketClientEvent event, SocketConnectable connectable, IOStream? connection) => {
if (event == SocketClientEvent.TLS_HANDSHAKING) {
((TlsClientConnection) connection).accept_certificate.connect ((peer_cert, errors) => {
// Return true to accept, false to reject
});
}
});
The errors are GLib.TlsCertificateFlags, so you'll want to determine which (if any) are acceptable. Ideally if there are any errors you would reject the certificate altogether, but if you want to allow self-signed certificates for example, that is possible this way.
You can simply check against the flags to see which ones are included in the errors:
TlsCertificateFlags[] flags = new TlsCertificateFlags[] {
TlsCertificateFlags.BAD_IDENTITY,
TlsCertificateFlags.EXPIRED,
TlsCertificateFlags.GENERIC_ERROR,
TlsCertificateFlags.INSECURE,
TlsCertificateFlags.NOT_ACTIVATED,
TlsCertificateFlags.REVOKED,
TlsCertificateFlags.UNKNOWN_CA
};
foreach (var flag in flags) {
if ((errors & flag) != 0) {
// The flag was included in the errors - respond accordingly
}
}
But when I try to connect 'developer.mozilla.org', I'm getting the
following error:
Resolved developer.mozilla.org to 54.192.235.2 Error performing TLS
handshake: A packet with illegal or unsupported version was received.
Can anybody tell me the reason why I am getting this error? (By the
way the version of GLib installed on my system is 2.64.6)
This is probably due to developer.mozilla.org using an old implementation of TLS (probably 1.0 or 1.1). These were disabled in GLib networking as of 2.64.x according to this bug report: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=954742
They may have upgraded to TLS 1.2 since you posted this question - I just did a quick test and connected using TLSv1.2 successfully.
Try run the program with export G_MESSAGES_DEBUG=all for full debug messages.
Also, for a full working example of code that uses TLS written in Vala via GIO, check out the code for this Gemini browser: https://github.com/koyuspace/fossil/blob/main/src/util/connection_helper.vala
I hope that this is somewhat useful to you.

Send data from ESP32 to a server via WiFi

I am not new here but this is my first question.
I have searched a lot and quite frankly can't understand how this is supposed to work.
I get data periodically (temperature) to my ESP32 and while having it set as a WiFi client, connect to my router and somehow store this data on my Laptop(or somewhere else, like a local/web site, don't know if that's possible/better).
How is the connection supposed to work? I have installed XAMPP and run the Apache and MySQL servers and I tried to connect to my Laptop with some sketches from Arduino using the ESP32 libraries
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
const char* host = "192.168.1.109"; //The local IP of my Laptop
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
but it doesn't connect.
Can someone please explain to me how this connection is supposed to take form or is this question too vague? I really just wanna know the "how-things-should-work-together" in this situation.
Thank you in advance.
OK, so after a lot of research and trying, I managed to work it out. I can now send an HTTP request (like GET or POST) from my ESP32 to a local server that is running on my laptop using XAMP and get a response. I can also connect to my local IP from my mobile phone (which is also in the same WiFi network).
Just for anyone else who wants to connect to a location in a server hosted on a PC in a local network, the steps are:
Create a local server on your PC, laptop whatever using an application like XAMPP (I have Windows 10 so WAMP would also work), download, install, open and start Apache.
Make sure that the Firewall lets your requests pass through (for me it was open by default, but I had seen elsewhere Firewall being an issue)
Go to your network settings, select the network that your devices(ESP32, phone, etc.)are connected and change its profile to Private, meaning that you trust this network, making your PC discoverable and able to accept requests. (That is really simple but took me hours to find)
Now, in order to connect from your phone to your PC, open a browser and enter the local IP (that is the IP that is given to your PC from the router as a local network name) of your PC to a browser and that's it, you are connected.
If you installed and ran XAMP, when connecting to your local IP(from same PC or other local device), it will forward you to 192.168.x.x/dashboard. If you want to create new workspaces and files, browse the XAMP folder in the installed location and inside the '/htdocs' subfolder do your testing.
For the ESP32 communication in Arduino(basic steps, not full code):
#include <WiFi.h>
#include <HTTPClient.h>
String host = "http://192.168.x.x/testfolder/";
String file_to_access = "test_post.php";
String URL = host + file_to_access;
void setup(){
WiFi.begin(ssid, password); //Connect to WiFi
HTTPClient http;
bool http_begin = http.begin(URL);
String message_name = "message_sent";
String message_value = "This is the value of a message sent by the ESP32 to local server
via HTTP POST request";
String payload_request = message_name + "=" + message_value; //Combine the name and value
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpResponseCode = http.sendRequest("POST", payload_request);
String payload_response = http.getString();
}
In the test_post.php (located in "C:\xampp\htdocs\testfolder\") file I used a simple script to echo a message received using a POST request, so it's only 'readable' from POST requests. Connecting to it from your browser will give you the "Sorry, accepting..." message.
<?php
$message_received = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$message_received = $_POST["message_sent"];
echo "Welcome ESP32, the message you sent me is: " . $message_received;
}
else {
echo "Sorry, accepting only POST requests...";
}
?>
Finally, using Serial prints, the output is:
Response Code: 200
Payload: Welcome ESP32, the message you sent me is: This is the value of a message sent by the ESP32 to local server via HTTP POST request
There it is, hope that this helps someone.

HTTPS SSL Connection not trusted, despite certificate being fine

I have got 2 sitest hosted on Windows 2012 R2 IIs 8.5.
One is instance of umbraco while other is .Net core based api (Lets call it MyApi).
I want to perform certain search action on umbraco so umbraco makes call to the api which calls back the Umbraco/Api. Call to the MyApi is fine, however the call from MyApi to the Umbraco/Api is problem. The Umbraco api logs:
Search failed System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
Certificates themselves are provided by our customer's inner authority, which is trusted root in server storage. Now originaly we have had problem with certificates, as they missed first DNS record we use for api call (the DNS records are not created yet, we use record in 'hosts') but that shoud be fiex by now.
I have updated the SSL error handler in the code so it logs an error and number in SSL Enum.
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
{
_logger.LogError("Received TLS errror " + ((int)sslPolicyErrors).ToString());
return false;
};
_logger.LogDebug("Search starting");
if (model.Username != null)
{
model.Favourites = _workplaceContext.GetUserFavourites(_dataContext, model.Username);
}
else if (model.JustFavourites)
{
return BadRequest();
}
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_configuration.GetValue<string>("UmbracoApiUrl"));
_logger.LogDebug("Searching for addres " + new Uri(_configuration.GetValue<string>("UmbracoApiUrl")));
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var json = JsonConvert.SerializeObject(model);
using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
{
var response = await client.PostAsync("workplace/search", stringContent);
if (response.IsSuccessStatusCode)
{
_logger.LogDebug("Search API Call success");
var jsonResponse = await response.Content.ReadAsStringAsync();
var responseModel = JsonConvert.DeserializeObject<SearchResponseModel>(jsonResponse);
_logger.LogDebug("Search response TotalCount = " + responseModel.TotalCount);
return responseModel;
}
else
{
_logger.LogDebug("Search API Call status - " + response.StatusCode);
return StatusCode((int)response.StatusCode);
}
}
}
Originaly we received number 2 error. Now we just receive number 0, which should be no problem. Despite that, connections is still not working. I have read various articles regarfding this and enabled troubleshooting through in web config of umbraco, but haven't found any useful information. I need method to troubleshoot the MyApi. Could somone point me a direction how to troubleshoot it to the similar degree of detail as umbraco (i am not much familiar with .NET core apps)?
The interesting part of error log:
2019-07-08 13:35:32.1745||DEBUG|XXXApi.Controllers.WorkplaceController|Search starting
2019-07-08 13:35:32.1901||DEBUG|XXXApi.Controllers.WorkplaceController|Searching for addres https://xxx.yy.zz/umbraco/api/
2019-07-08 13:35:32.2682||ERROR|XXXCApi.Controllers.WorkplaceController|Received TLS errror 0
2019-07-08 13:35:32.2682||ERROR|XXXApi.Controllers.WorkplaceController|Search failed System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.PooledStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
Solution: The original error was in certificate and got fixed, BUT the callback returning false I used for debugging caused problem marking connection unsuccessful. It took like 2 days to figure it out. So since moment i got 0 in enum, it was just bug in my debugging code.
Oh and don't forget to unsubscribe the delgate.

How to send text from Windows Phone 8.1 via HttpWebRequest / POST?

I have a web service that expects (unicode UTF-8 encoded) text data as an HTTP POST message.
I'd like to use it from a Windows Phone 8.1 runtime client.
I created the client, but it does not invoke the web URI.
Here's the code I use on the client:
Can anyone tell what am I missing?
Thanks,
B
{
...
SendText("http://192.168.1.107:58709/UploadText.aspx"); // The IP belongs to the web server, port is correct. I can invoke it from a browser.
...
}
string StringToSend = "This is a test string uploaded via HTTP POST from WP8";
private void SendText(string Url)
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(Url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(UploadText_GetRequestStreamCallback), request);
}
public void UploadText_GetRequestStreamCallback(IAsyncResult asyncResult)
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)asyncResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asyncResult);
byte[] postDataAsBytes = System.Text.Encoding.UTF8.GetBytes(StringToSend);
postStream.Write(postDataAsBytes, 0, postDataAsBytes.Length);
postStream.Flush();
// postStream.Close(); // Close is not available in Windows Phone 8.1 runtime project.
// request.ContentLength = postDataAsBytes.ToString(); // request.ContentLength is not available in Windows Phone 8.1 runtime project.
request.Headers["Content-length"] = postDataAsBytes.ToString();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
OK, it seems the code was correct...
Problem was, that the phone emulator could not connect to the development server (IIS Express). I searched the web over, tried a number of solutions, but I could not make it happen. In the meantime I trashed my wifi connection, had to remove and reinstall Hyper-V to make it work again.
The workaround was to publish the test web app to the local IIS (make sure it is the Debug version that is published) then attach to it from the debugger, call from WP8.1 emulator - and it works.

Netty client acting as a service

I am currently working on a client-server application using netty, some of the clients are not going to be doing anything until they recieve a message. I have read the api and can´t find a way to do so. I mean I could try to have "in.readline()" on the main so it won´t end but it Doesn´t feel right. Also could have endless loops but I don´t think its the right way either.
The question here is: is there a way to bind the socket for incoming messages just like the server having the main method ending?
public void run(){
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChatClientInitializer());
Channel channel = bootstrap.connect(host,port).sync().channel();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Inserte su nombre");
String nombre = in.readLine();
MyClientChannel canal = new MyClientChannel(channel,nombre);
canal.write("SM",nombre);
in.readLine();
See that at the end I had to write "in.readline()" so the program wouldn´t end and the handler would be still up for incomming messages
The easiest thing to do would be to replace:
in.readLine();
With:
channel.closeFuture().await();
When the connection to the server is disconnected, the client will terminate.
You will also want to spend some time defining your client's life-cycle, so that the channel's state doesn't affect when your application is running and when it's not.

Resources