How to disable soReusePort in gRPC C# Channel? - c#

I'm trying to build a load test application for a Grpc server. I would like the channels to open different ports whenever trying to connect to the server with disabling "SoResuePort Channel Option". By using the following code:
string Host = "192.168.1.20";
int Port = 7081;
IEnumerable<ChannelOption> options = new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) };
ChannelOne = new Channel(Host, Port, ChannelCredentials.Insecure , options);
ChannelTwo = new Channel(Host, Port, ChannelCredentials.Insecure , options);
await ChannelOne.ConnectAsync();
await ChannelTwo.ConnectAsync();
I expect gRPC to open a new TCP connection per channel, but it's reusing the same TCP connection.

Related

Connecting from home Windows computer or Windows EC2 server to a Ubuntu MongoDB EC2 server via SSH and port forwarding?

I have two AWS EC2 instances:
Windows Server which will handle user requests for data.
Ubuntu server with MongoDB database on it to be accessed and manipulated by Windows Server.
I am attempting to write a program in C# .NET that will be able to connect to the Ubuntu server and its MongoDB when run from my local computer or from the Windows Server.
I am using Renci SSH.NET and the standard MongoDB driver. The MongoDB driver operation is explained here. For networking, I found one old guide here which helped me get part way. I have so far:
string SSHServerUserName = "ubuntu";
string SSHServerHost = "x.xx.xxx.xxx"; //public IP of ubuntu server as per AWS
PrivateKeyFile keyFile = new PrivateKeyFile(#"H:\MongoDB.pem", "filePass"); //mongo server AWS keyfile
PrivateKeyAuthenticationMethod authenticationMethod = new PrivateKeyAuthenticationMethod(SSHServerUserName, keyFile);
ConnectionInfo connectionInfo = new ConnectionInfo(SSHServerHost, SSHServerUserName, authenticationMethod); //uses DefaultPort = 22
SshClient sshClient = new SshClient(connectionInfo);
//sshClient.ErrorOccurred += delegate { Debug.WriteLine("SSH ERROR OCCURRED"); };
//sshClient.HostKeyReceived += delegate { Debug.WriteLine("SSH HOST KEY RECEIVED"); };
sshClient.Connect();
if (sshClient.IsConnected) {
string MongoDBHost = "xx.xx.xx.xx"; // **PRIVATE IP OF UBUNTU AWS EC2?
uint MongoDBPort = 27017;
ForwardedPortLocal forwardedPortLocal = new ForwardedPortLocal("127.0.0.1", 5477, MongoDBHost, MongoDBPort);
//forwardedPortLocal.Exception += delegate { Debug.WriteLine("FORWARDED PORT LOCAL EXCEPTION"); };
//forwardedPortLocal.RequestReceived += delegate { Debug.WriteLine("FORWARDED PORT REQUEST RECEIVED"); };
sshClient.AddForwardedPort(forwardedPortLocal);
forwardedPortLocal.Start();
MongoClientSettings mongoSettings = new MongoClientSettings();
mongoSettings.Server = new MongoServerAddress("localhost", 5477); //IS THIS RIGHT?
MongoClient mongoClient = new MongoClient(mongoSettings);
var iMongoDatabase = mongoClient.GetDatabase("test");
var profiles = iMongoDatabase.GetCollection<BsonDocument>("profiles");
Debug.WriteLine("GOT THE COLLECTION:"); //debugs out okay...
var document = new BsonDocument {
{ "name", "userName" },
{ "type", "newUser" },
{ "count", 1 },
{ "info", new BsonDocument
{
{ "x", 203 },
{ "y", 102 }
} }
};
profiles.InsertOne(document); //reports time out exception if using try/catch
Debug.Write("ATTEMPTED TO INSERT ONE");
}
I am getting sshClient.IsConnected() as true. However, I do not know if my forwarded port is working correctly or to what extent it is or isn't connecting to the Mongo Database. I can see from MongoDB Compass (GUI database navigator) nothing is being inserted, and from a try catch statement I can receive the exception that the MongoDB driver times out on the InsertOne command.
Questions:
How do I test the Forwarded Local Port? I see FORWARDED PORT REQUEST RECEIVED outputs but don't know if they're working.
Is the MongoDB server code (IPs, ports, "localhost") correct for this configuration? How do I test to see if it has connected properly to the database?
What is going wrong in the above?
This is my first database and EC2 configuration. Thanks for any help.

Timeout in socket connection in UWP

I have this code which works fine for project type of Console App (.NET Core).
class Program
{
static void Main(string[] args)
{
var L = new TcpListener(IPAddress.Any, 4994);
L.Start();
using (var C = L.AcceptTcpClientAsync().Result)
{
var S = C.GetStream();
var BR = new BinaryReader(S);
var BW = new BinaryWriter(S);
BW.Write("This is from Console!!!");
Console.WriteLine(BR.ReadString());
}
}
}
But when I use this code in project type of Blank App (Universal Windows) like this:
public MainPage()
{
InitializeComponent();
ThreadPool.RunAsync(foo);
}
static void foo(IAsyncAction operation)
{
var L = new TcpListener(IPAddress.Any, 4994);
L.Start();
using (var C = L.AcceptTcpClientAsync().Result)
{
var S = C.GetStream();
var BR = new BinaryReader(S);
var BW = new BinaryWriter(S);
BW.Write("This is from UWP!!!");
Debug.Write(BR.ReadString());
}
}
It will listen to that port when I check it by netstat but when the client wants to connect this exception will be thrown.
System.Net.Sockets.SocketException: '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'
The UWP App has Private Networks (Client & Server) and Internet (Client & Server) capabilities.
Turning firewall on and off didn't help.
Target Version: Windows 10 Creators Update (10.0; Build 15063)
Client Code which is a WPF application:
using (var C = new TcpClient("127.0.0.1", 4994))
{
var S = C.GetStream();
var BR = new BinaryReader(S);
var BW = new BinaryWriter(S);
BW.Write("This is a test");
MessageBox.Show(BR.ReadString());
}
Debugging UWP & TCP listeners from localhost has always been problematic. Your code is OK and it should work if you try to connect into it from an external computer. The issue you're seeing is quite likely a bug/hyper-v issue/networking problem in the network isolation.
You can check if the network isolation for your app is enabled (it is by default) running the following from command prompt:
CheckNetIsolation.exe LoopbackExempt -s
My recommendation is to use an external computer to make sure that your code is fine (it should be). After that you can try to fight with the network isolation but that can be frustrating.
Here's an another issue where this has been discussed: Unable to access TCP Server inside a Windows Universal Application

UWP nativemessaging host print to network printer using sockets in C#

We are trying to build an UWP app with native messaging where the user will print labels on their network printers. Here is the code
string printerIPAddress = msg.ipAddress;
int printerPort = msg.port;
IPAddress addr = IPAddress.Parse(printerIPAddress);
IPEndPoint remoteEP = new IPEndPoint(addr, printerPort);
Socket clientSock =
new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
byte[] zplBytes = Encoding.ASCII.GetBytes((string)msg.zplText);
clientSock.Connect(remoteEP);
var bytesSent = clientSock.Send(zplBytes, zplBytes.Length, 0);
I am getting the following error:
Exception thrown:
'System.Net.Internals.SocketExceptionFactory.ExtendedSocketException'
in System.Net.Sockets.dll
System.Net.Internals.SocketExceptionFactory+ExtendedSocketException:
An attempt was made to access a socket in a way forbidden by its access permissions
We have built similar native messaging app for chrome and FF and we can print using network printer without any issue.

Windows 8 app how to connect to Socket server

i have done a server using this example socketAsyncEventArgs
in visual studio 2010 and .net 4.0.
Now i'm trying to connect to it from a windows 8 app using StreamSocket but i'm getting a "Acces denied" message.
here is the Client code:
private StreamSocket streamSocket;
public string Server = "192.168.0.101";
public int Port = 9900;
public async void Connect()
{
streamSocket = new StreamSocket();
Connect();
try
{
await streamSocket.ConnectAsync(
new Windows.Networking.HostName(Server),
Port.ToString()); // getting Acces Denied here
DataReader reader = new DataReader(streamSocket.InputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;
while (true)
{
var bytesAvailable = await reader.LoadAsync(1000);
var byteArray = new byte[bytesAvailable];
reader.ReadBytes(byteArray);
}
}
catch (Exception e)
{
MessageBox(e.StackTrace);
}
}
How to fix the problem? Is there another way to send and receive messages using this server?
You are probably also seeing the following as part of your error message:
WinRT information: A network capability is required to access this network resource
This is because you need to add a capability to your application that allows you to access local networks. Double click on the Package.appxmanifest file in your project. Click on the Capabilities tab. Add the Private Networks (Client & Server) capability to your project.

Raw FTP SSL with C#

I'm trying to understand how SSL works. In my wish to make a small FTP client which supports SSL I've run into some problems:
TcpClient FtpConnection = new TcpClient(FtpServer, FtpPort);
NetworkStream FtpStream = FtpConnection.GetStream();
StreamReader FtpReader = new StreamReader(FtpStream);
FtpWriter = new StreamWriter(IrcStream);
send_cmd("AUTH SSL");
send_cmd is just a FtpWriter.WriteLine(text); FtpWriter.Flush(); function.
My "problem" is this: First I need to make a (non-ssl) connection to the FTP, then tell it to do a ssl connection (AUTH SSL), and I would guess I then need to make a new connection - something like:
TcpClient client = new TcpClient(FtpServer, FtpPort);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
try
{
sslStream.AuthenticateAsClient("foobar");
}
catch (AuthenticationException e)
{
MessageBox.Show("Authentication failed - closing the connection.");
client.Close();
return;
}
Taken from msdn.
I keep dying on handshake failed due to unexpected packet format (which I've tried googling, but all say it's because the author has connected to a wrong port), which I take as: The connection is not ssl until AUTH SSL is send to it. So my question is, how would i go about making this a "hybrid" connection so I can make an SSL connection to the server?
Any help is greatly appreciated!
Using a library like that is the opposite of what I wanted. Since I found so few hits when searching the web, I'll post what I figured out:
Building a C# ftp client is basically like so:
TcpClient blabla = new TcpClient("some.host", 21);
NetworkStream blabla_stream = blabla.GetStream();
StreamReader unsecure_reader = new StreamReader(blabla_stream);
StreamWriter blabla_writer = new StreamWriter(blabla_stream);
blabla_writer.WriteLine("AUTH SSL");
string response = "";
while ((response = unsecure_reader.ReadLine()) != null)
{
if (response.Substring(0,3) == "234")
{
SslStream ssl_connection = new SslStream(blabla.GetStream(), false, new RemoteCertificateValidationCallback(validate_certificate), null);
ssl_connection.AuthenticateAsClient("");
StreamReader ssl_stream = new StreamReader(ssl_connection);
ftp_writer = new StreamWriter(ssl_connection);
}
}
where validate_certificate is a function based on msdn's (you can google it and mod it easily yourself).
For more info see RFC 4217 and 2228.
http://ftps.codeplex.com/
This project contains every pieces you need.

Categories