how can a network programming solution be tested at home? - vb.net

I have a program used for the online multi-playing of sudoku (don't ask). I have written the code devoted to setting up specific tcpclient connections between instances of the application but when I tried to test it using the local host (IP:127.0.0.1) I got the error message:
"no connection could be made because the target machine actively refused it"
just when trying to set-up the client. regardless, it uses the same port to listen as to send and so later on this method would run into trouble but i need to test my solution so i ask: what is the easiest way (time is a factor) to test a network program at home. i have access to the following:
1 computer with the database installed via xampp (database is necessary)
up to 2 other computers without the database (could maybe be installed)
thank you.
edit:
'sets the destination IP to the HostAddress
IP = sender.CurrentRow.Cells.Item("HostAddress").Value
'creates a new instance of a client for send and recieving streams
client = New TcpClient(IP, port)
this is how I initialise the client. it is in the sub that a datagridview cell is clicked and HostAddress contains the IP address of the host as a string. it is the second line where the exception happened.

You provided too little information to actually help you find a bug, but here is how you can try if a basic connection on localhost works on your PC. Create two console projects, one the client and one server and insert the following code:
Client
Imports System.Net.Sockets
Imports System.Net
Module Client
Sub Main()
Dim IP As IPAddress = IPAddress.Parse("127.0.0.1")
Console.WriteLine("Start server and then press any key to connect.")
Console.ReadKey()
Console.WriteLine("Connecting...")
Dim client As New Net.Sockets.TcpClient
client.Connect(IP, 6583)
Console.WriteLine("Connected!")
Console.ReadKey()
client.Close()
End Sub
End Module
Server
Imports System.Net.Sockets
Imports System.Net
Module Server
Sub Main()
Dim IP As IPAddress = IPAddress.Parse("127.0.0.1")
Dim server As New TcpListener(IP, 6583)
server.Start()
Console.WriteLine("Waiting for connection...")
While server.Pending = False
End While
Dim connectedclient As TcpClient = server.AcceptTcpClient
Console.WriteLine("Client connected. Nice.")
Console.ReadKey()
End Sub
End Module
Compile and start the projects. Once the server starts it starts listening on port 6583 on localhost. Start the client and press a key and you should see messages saying that the connection works.
If it does, you code is faulty. If it doesn't you should check your firewall settings and stuff like this.

Related

The remote certificate is invalid according to the validation procedure: RemoteCertificateNotAvailable when trying to connect tcp/ip

I am trying to learn some secure client / server programming. I am using .NET CORE 7, VS 2022 Pro, on Windows 11. I found the following example at MS showing how to establish a connection using TLS.
https://learn.microsoft.com/en-us/dotnet/api/system.net.security.sslstream?view=net-6.0
I bought a cheap cert from COMODO and installed it into my Machine Personal Store. When I click on it there is a private key embedded in the certificate.
I did modify the code from the example above to pull the certificate from the store on the machine instead of loading it from a file...
Public Function getServerCert() As X509Certificate2
Dim store As X509Store = New X509Store(StoreName.My, StoreLocation.LocalMachine)
store.Open(OpenFlags.[ReadOnly])
Dim foundCertificate As X509Certificate2 = Nothing
For Each currentCertificate As X509Certificate2 In store.Certificates
If currentCertificate.IssuerName.Name IsNot Nothing AndAlso currentCertificate.Subject.Equals("CN=<certname>") Then
foundCertificate = currentCertificate
Exit For
End If
Next
Return foundCertificate
End Function
This is my Authenticate line of code...
sslStream.AuthenticateAsServer(getServerCert, clientCertificateRequired:=True, SslProtocols.Tls12 Or SslProtocols.Tls13, checkCertificateRevocation:=True)
RaiseEvent Output("Client has connected!")
The issue I am running into is on the server when the client attempts to connect I receive this error:
"The remote certificate is invalid according to the validation
procedure: RemoteCertificateNotAvailable"
I have been pulling my hair out for hours trying to get past this error. Can anybody assist in what this means and how I can possibly fix it? I am running the client and server both from the same machine as I develop it (not sure if that makes a diff) but I did try running the client from a different machine and still got the same error.
Thanks!

VB.Net checking if a port is open and accepting connections

I'm writing a VB.Net app which connects to a remote server and listens for data on that port.
I've got the following function which checks that the IP/port in question is listening for connections or not. When the process on the remote port is running is works fine but when it's not running rather than the exception handler running I get an ugly dialogue box in Visual Studio rather when I run it.
Any ideas why the exception handler is not firing ?
Private Function testSelectedPort(ip As String, port As Integer) As Boolean
' Function to open a socket to the specified port to see if it is listening
' Connect to socket
Dim testSocket As New System.Net.Sockets.TcpClient()
Try
testSocket.Connect(ip, port)
' The socket is accepting connections
testSocket.Close()
Return True
Catch ex As Exception
' The port is not accepting connections
Return False
End Try
Return False
End Function
The error that's being thrown in "No connection could be made because the target machine actively refused it" and it's being thrown at the testSocket.Connect(ip, port) line.
I thought that it would execute the code in the Catch section if it failed to connect ?
Once the exception is thrown it should be handled by the Catch-block. There are only a few exceptions that are generally not very easy to handle via Try/Catch (for instance a System.AccessViolationException), but those do not include the errors a socket might throw.
Please make sure that you haven't ticked the specific exception type to break when thrown, in the Exception Settings window

TcpListener actively refused connection

I am maintaining an application that uses a TcpListener to listen for incoming communication. The following code opens the connection:
Dim listener As TcpListener
_listenFailed = False
Try
listener = New TcpListener(System.Net.IPAddress.Parse(Me.Host), Me.Port)
listener.Start()
Catch ex As Exception
' an error here means the settings are likely bogus
_listenFailed = True
Return
End Try
While Not _stoplistening
{
' Accept connection
}
The problem that I am having is that when i send a file from a different computer, I get the error "No connection could be made because the target machine actively refused it."
I have checked for firewalls and antivirus, and there were no blocks. I used
netstat -a -n
to determine that the port is active and listening. Both applications are running from Visual Studios in Administrator mode, not that this should make a difference. I have a break point set at the first line of the accept connection code, but it never gets run.
I stopped the application and examined the TcpListener, and found that there were a couple errors if I dug deep down. At TcpListener.LocalEndpoint.IPEndPoint.IPAddress.Address.ErrorCode there was the error 10045, "OperationNotSupported". Also, at TcpListener.Socket.RemoteEndPoint.ErrorCode there was an error 1057, "A request to send or receive data was disallowed because the socket is not connected, and (when sending on a datagram socket using a sendto call) no address was supplied. I don't know if either of these errors are relevant.
If anyone has any insights as to what might be causing this problem, or steps that can be taken to trace the root of the issue, I would be grateful.
Try changing this:
listener = New TcpListener(System.Net.IPAddress.Parse(Me.Host), Me.Port)
To this:
listener = New TcpListener(System.Net.IPAddress.Any, Me.Port)
This will allow you to listen across all network interfaces.
Additionally, you can use IPv6Any instead of Any if you want to target IPv6 instead. This choice has an impact on the address used by the client side obviously.

Difference between new TcpClient(MachineName, port) and new TcpClient(new IPEndpoint(..., Port))

Hej Hej,
I have a .Net program that has to run on a cluster of server 2008.
To find out the right IP I resolve the dns by
GetHostEntry(VarDefinedInfConfig).AddressList(0)
but when I am converting my old code (this code picks the wrong IP) dns.GetHostName().AddressList(0) => this returns a virtual IP and not the right one.
So I changed my TcpListener to (dns is parameter from config)
Dim listener As TcpListener = New TcpListener(New IPEndPoint(Net.Dns.GetHostEntry(dns).AddressList(0), 8001))
listener.Start()
In the old way a tcpclient was defined by this code
Dim client As TcpClient = New TcpClient(Environment.MachineName, 8001)
Console.WriteLine("Done...")
client.Close()
This also connects to the wrong IP so I found the overload of TcpClient and used that one
New way:
Dim client2 As TcpClient = New TcpClient(New IPEndPoint(Net.Dns.GetHostEntry(dns).AddressList(0), 8001))
Console.WriteLine("Done")
client2.Close()
But when I use the second one I got the exception "Only one usage of each socket address (protocol/network address / port) is normally permitted.
Weird thing is if I get the IP from the MachineName is exactly the same as the ip retreived from dns with parameter.
Does anybody know the cause of this exception? Normally they should have the same result.
Greetz,
Jonathan
Is it possible that you overlooked the main difference between the 2 mentioned TcpClient constructors (MSDN)?:
TcpClient(String, Int32) .. connects to the specified port on the specified host.
TcpClient(IPEndPoint) .. binds it to the specified local endpoint.
So effectively, with the first constructor a socket is opened on an available, "OS-assigned" local port and then connected to the server, whose address or DNS-name and port are passed in as arguments; after that you're ready to send or receive data.
With the second constructor a socket is just opened on a certain local port (which is identified in the endpoint argument), but that's all - no connection to any [remote, or even local] server is made, because no server info is known yet; you'd need to call one of Connect(.) methods before making any comm operations (similar to the workaround you found).
Why don't you specify the correct IP in the application config?
Only one usage of each socket address (protocol/network address / port) is normally permitted
Means that someone (your or another application) is already listening on that ip/port.
Right now I use an work arround. I create an TcpClient() with an empty constuctor and then I use the Connect(IPendpoint) and this works.

Ensure a windows service is started from Visual Basic .Net

I have a WCF service being hosted in a Windows Service (using techniques discussed here) and it works great. I'm now writing a (VB.Net) frontend app that needs to call that service, but I don't want my users having to fiddle around with the services snap-in and starting the service manually.
Can I write some code to ensure the Windows Service is started, or start it if it isn't?
Edit: OF course, I can ensure the Service startup is set to automatic, but it doesn't need to be running all the time, and even then the frontend app still needs to be sure the service is running and start it if it isn't.
You can use the ServiceController class to manipulate a service as needed.
Example from MSDN using the Status property to check if a service needs to be started:
' Toggle the Telnet service -
' If it is started (running, paused, etc), stop the service.
' If it is stopped, start the service.
Dim sc As New ServiceController("Telnet")
Console.WriteLine("The Telnet service status is currently set to {0}", sc.Status)
If sc.Status.Equals(ServiceControllerStatus.Stopped) Or sc.Status.Equals(ServiceControllerStatus.StopPending) Then
' Start the service if the current status is stopped.
Console.WriteLine("Starting the Telnet service...")
sc.Start()
Else
' Stop the service if its status is not set to "Stopped".
Console.WriteLine("Stopping the Telnet service...")
sc.Stop()
End If
' Refresh and display the current service status.
sc.Refresh()
Console.WriteLine("The Telnet service status is now set to {0}.", sc.Status)
You can do something like
Dim controller As New ServiceController("ServiceNameHere")
If controller.Status = ServiceControllerStatus.Stopped Then
controller.Start()
End If
Remember to add reference to and import System.ServiceProcess