How to check for blocked ports with VB.NET - vb.net

I have been given the task of creating a small application in VB.NET where users can enter a port number into a text field and it checks against the machines IP address to see if that port is blocked or not. I did develop a method using a TCPListener, but it seems it is not working as it needs to be. Currently i have:
Dim tcpList As TcpListener = New TcpListener(System.Net.IPAddress.Parse(Host), PortNumber)
tcpList.Start()
tcpList.Stop()
Return True
However that seems to show the Port as blocked if something is already listening in on it. Can anybody think of a way of doing this properly?
Thanks!

Try this:
If My.Computer.Network.Ping("198.01.01.01") Then
MsgBox("Server pinged successfully.")
Else
MsgBox("Ping request timed out.")
End If
Or
If My.Computer.Network.Ping("www.cohowinery.com", 1000) Then
MsgBox("Server pinged successfully.")
Else
MsgBox("Ping request timed out.")
End If
also see:https://msdn.microsoft.com/en-us/library/s9xkzk4s(v=vs.90).aspx

Related

While Download Works But Post Request Not (Chilkat)

I am facing a very wired issue, and passed so many hours to find the issue but without any luck :(
i have setup a web server on my mobile (android)..
and trying to use that using my vb application
where i simple call Download method on the very sample url (same ip/port), it works and save the response body as downloaded file.
but when i try to send post command it is not working, it gives error "Connection rejected"
here is the code to download:
objDHTTP.Download("http://192.168.1.101:8000/fileAdmin.php", strAppDir & "\wtf-response.txt")
here is the code when i tried to use same url and port for post request:
objDRequest.Path = "/fileAdmin.php"
objDRequest.AddParam("fileAction", "Upload")
objDRequest.AddParam("fileName", "DB.sql")
objDRequest.AddFileForUpload("adminFile", strAppDir & "\c.dll")
objDResponse = objDHTTP.SynchronousRequest(strServerIP, 8000, False, objDRequest)
but it does not works and throws above error
here is the success response (for download method):
<ChilkatLog>
<Download>
<DllDate>Dec 21 2018</DllDate>
<ChilkatVersion>9.5.0.76</ChilkatVersion>
<Architecture>Little Endian; 32-bit</Architecture>
<Language>.NET 4.0</Language>
<VerboseLogging>0</VerboseLogging>
<url>http://192.168.1.101:8000/fileAdmin.php</url>
<toLocalPath>G:\wtf-sucess.txt</toLocalPath>
<currentWorkingDir>G:\</currentWorkingDir>
<a_httpDownload>
<httpDownloadFile>
<localFilePath>G:\wtf-sucess.txt</localFilePath>
<localFileAlreadyExists>1</localFileAlreadyExists>
<quickHttpRequest>
<httpVerb>GET</httpVerb>
<url>http://192.168.1.101:8000/fileAdmin.php</url>
<openHttpConnection>
<info>Opening connection directly to HTTP server.</info>
<httpHostname>192.168.1.101</httpHostname>
<httpPort>8000</httpPort>
<tls>False</tls>
<info>HTTP connection succeeded.</info>
</openHttpConnection>
<buildQuickRequest>
<genStartLine>
<startLine>GET /fileAdmin.php HTTP/1.1</startLine>
</genStartLine>
<addCookies>
<info>Not auto-adding cookies.</info>
<sendCookies>1</sendCookies>
<cookieDir></cookieDir>
</addCookies>
</buildQuickRequest>
<sendRequestHeader>
<sendHeaderElapsedMs>0</sendHeaderElapsedMs>
</sendRequestHeader>
<statusCode>200</statusCode>
<statusText>OK</statusText>
<checkCloseConnection>
<info>Response includes connection:close header (or proxy-connection:close header)</info>
</checkCloseConnection>
</quickHttpRequest>
<outputLocalFileSize>26</outputLocalFileSize>
<numOutputBytesWritten>26</numOutputBytesWritten>
</httpDownloadFile>
</a_httpDownload>
<totalElapsedMs>47</totalElapsedMs>
<ContentLength>0</ContentLength>
<info>Success.</info>
</Download>
</ChilkatLog>
And here is the error/fail response (for post request):
<ChilkatLog>
<SynchronousRequest>
<DllDate>Dec 21 2018</DllDate>
<ChilkatVersion>9.5.0.76</ChilkatVersion>
<Architecture>Little Endian; 32-bit</Architecture>
<Language>.NET 4.0</Language>
<VerboseLogging>0</VerboseLogging>
<domain>191.168.1.101</domain>
<port>8000</port>
<ssl>0</ssl>
<httpRequest>
<httpVersion>1.1</httpVersion>
<verb>POST</verb>
<path>/fileAdmin.php</path>
<contentType>multipart/form-data</contentType>
<charset>windows-1252</charset>
<sendCharset>0</sendCharset>
<mimeHeader></mimeHeader>
<requestParams>
<requestItem>
<name>fileAction</name>
<value>Upload</value>
</requestItem>
<requestItem>
<name>fileName</name>
<value>DB.sql</value>
</requestItem>
<requestItem>
<name>adminFile</name>
<fileOnDisk>G:\c.dll</fileOnDisk>
<numValueBytes>8697</numValueBytes>
</requestItem>
</requestParams>
</httpRequest>
<fullRequest>
<a_synchronousRequest>
<generateRequestHeader>
<httpRequestGenStartLine>
<genStartLine>
<startLine>POST /fileAdmin.php HTTP/1.1</startLine>
</genStartLine>
</httpRequestGenStartLine>
<addCookies>
<info>Not auto-adding cookies.</info>
<sendCookies>1</sendCookies>
<cookieDir></cookieDir>
</addCookies>
<genMultipartFormData>
<requestParam>
<name>fileAction</name>
</requestParam>
<requestParam>
<name>fileName</name>
</requestParam>
<requestParam>
<name>adminFile</name>
<filename>G:\c.dll</filename>
</requestParam>
</genMultipartFormData>
</generateRequestHeader>
<fullHttpRequest>
<domain>191.168.1.101</domain>
<port>8000</port>
<ssl>0</ssl>
<openHttpConnection>
<info>Opening connection directly to HTTP server.</info>
<httpHostname>191.168.1.101</httpHostname>
<httpPort>8000</httpPort>
<tls>False</tls>
<socket2Connect>
<connect2>
<connectSocket>
<connect_ipv6_or_ipv4>
<info>Connection attempt failed.</info>
<maxWaitTimeMs>10000</maxWaitTimeMs>
<totalMsWaitedSoFar>2100</totalMsWaitedSoFar>
</connect_ipv6_or_ipv4>
<connect_ipv6_or_ipv4>
<info>Connection attempt failed.</info>
<maxWaitTimeMs>10000</maxWaitTimeMs>
<totalMsWaitedSoFar>2150</totalMsWaitedSoFar>
</connect_ipv6_or_ipv4>
</connectSocket>
<ConnectFailReason>Connection rejected</ConnectFailReason>
<error>A few possible causes for a connection being rejected are:</error>
<error>- A firewall (software or hardware), such as Windows Firewall, is blocking the connection .</error>
<error>- Nothing is listening at the remote host:port</error>
</connect2>
</socket2Connect>
</openHttpConnection>
</fullHttpRequest>
<success>0</success>
</a_synchronousRequest>
<success>0</success>
</fullRequest>
<totalTime>Elapsed time: 4390 millisec</totalTime>
<error>Failed.</error>
</SynchronousRequest>
</ChilkatLog>
can any one tell me what could be the reason for this?
thanks in advance
best regards
The likely reasons are present in the LastErrorText:
<ConnectFailReason>Connection rejected</ConnectFailReason>
<error>A few possible causes for a connection being rejected are:</error>
<error>- A firewall (software or hardware), such as Windows Firewall, is blocking the connection .</error>
<error>- Nothing is listening at the remote host:port</error>
My guess is that the Windows Firewall is blocking the outbound POST.
This example shows the errors one would get for various TCP socket connection problems: https://www.example-code.com/vbnet/socket_connect_fail.asp

How does PerformanceCounter count current connections to IIS website?

We can use C# code or performance monitor in windows server to view current connections to IIS website.
PerformanceCounter performanceCounter = new System.Diagnostics.PerformanceCounter();
performanceCounter.CategoryName = "Web Service";
performanceCounter.CounterName = "Current Connections";
performanceCounter.InstanceName = "SMS_Collection_CFC";
string data = string.Format("{0}\t{1} = {2}", performanceCounter.CategoryName,
performanceCounter.CounterName, performanceCounter.NextValue());
This can return the connections number.
Is this counting the TCP connections under the hood? We know there are many TCP connection status like ESTABLISHED,TIME_WAIT, which status is performance counter counting?
Since nobody answers this post, I post my findings.
In the server, I invoke the related code in the original post, and it returns 574.
string data = string.Format("{0}\t{1} = {2}", performanceCounter.CategoryName,
performanceCounter.CounterName, performanceCounter.NextValue());
And then, I run the netstat command.The website is ocupying port 9010.
netstat -an | find /i "9010"
It returens 550 established TCP connections. So I guess it is monitoring established TCP connections.

Server listening

I'm working with VB.NET
So I have a server that broadcast it's own IP every second
Private Sub IPBroadcastTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IPBroadcastTimer.Tick
BroadcastIP()
End Sub
Do I have to keep broadcasting it every second for clients to pick it up after several minutes or hours?
If so, how would I set the server to listen to logins?
Here's what happens client-side and server-side:
Server : "Broadcasts IP every second" > "Listens to incoming transmissions" > "receives 3 strings [username/pass/ip]" > "Checks username and password validity on local XML file" > "sends confirmation or denial to target IP"
Client : "Listens to server broadcast" > "Receives Server IP" > "Sends 3 Strings through a form: username, password and local IP" > "Listen to server's confirmation or denial"
I used this to send, but listening doesn't seem to work...
Public EndPoint As New IPEndPoint(IPAddress.Parse("255.255.255.255"), 1001) ''Send destination port
Public EndPoint2 As New IPEndPoint(IPAddress.Any, 2001) ''Receive destination port
Public UserIPEndPoint As New IPEndPoint(IPAddress.Any, 2001)
Public UsernameEndPoint As New IPEndPoint(IPAddress.Any, 2001)
Public PassEndPoint As New IPEndPoint(IPAddress.Any, 2001)
Public Send As New UdpClient(2001) ''Send source port
Public Receive As New UdpClient(1001) '' Receive source port
Sending:
Send.Send(IPInBytes, IPInBytes.Length, EndPoint)
Receiving:
Receive.Receive(UserIPEndPoint)
How do I solve this?
What is the purpose of the broadcast? If it is for consumers to detect the service, perhaps it's better to rely on already developed protocols for this (such as Bonjour or SSDP). Like in at least SSDP, a consumer can broadcast a question ("is anybody there?") to which services may reply. Services may also spontaneously broadcast their presence, for instance when they are started, so that consumers with an ongoing detection can find them.

WebDAV & Exchange 2003 - works in debug, fails without

So I have a very weird problem.
I am writing some code in VB.Net under .NET 2.0 which interfaces with MS Exchange 2003. Because of the Exchange 2003 "requirement" I am forced to write this code using WEBDAV.
The code itself is replicating, to some degree, a schedule management process. It's creating Appointments on the Exchange Server in response to inputs from the user and managing it's data internally in a SQL Server database.
The problem situation is this: A new person is assigned to be in charge of a meeting. The requirement says the program should generate a meeting cancellation request to the person removed from the meeting (if such a person existed) and a meeting request sent to the new person.
In the case of there being an existing person, what appears to happen is this:
The meeting cancellation request
gets sent
Exchange barfs and returns status code 500 (internal server error) during the set of
requests which send the meeting request to the new person.
However! While debugging this particular scenario, it works just fine for me, if I step through the code in the Visual Studio debugger. Left to it's own devices, it fails every time.
Just for yuk's sake, I added a Thread.Sleep(500) to the part after sending the cancellation request, and Exchange doesn't barf anymore...
So, my question!
If adding a Thread.Sleep to the code causes this error to go away, a race condition is implied, no? But, my code is running under a web application and is a totally single threaded process, from start to finish. The web requests I am sending are all in synchronous mode so this shouldn't be a problem.
What would I do next to try and track down the issue?
Try and divine if the race condition itself is in the .Net 2.0 BCL networking code?
Try and do some debugging on the Exchange server itself?
Ignore it, be glad the Thread.Sleep masks the problem and keep on going?
Any further suggestions would be wonderful.
In response to comment, I can post the failing function:
Private Shared Sub UpdateMeeting(ByVal folder As String, ByVal meetingId As String, ByVal oldAssignedId As String, ByVal newAssignedTo As String, ByVal transaction As DbTransaction)
If String.IsNullOrEmpty(meetingId) Then
Throw New Exception("Outlook ID for that date and time is empty.")
End If
Dim x As New Collections.Generic.List(Of String)
If oldAssignedId <> newAssignedTo AndAlso Not String.IsNullOrEmpty(oldAssignedId) Then
'send cancellation to old person
Dim lGetCounselorEmail1 As String = GetCounselorEmail(oldAssignedId, transaction)
Common.Exchange.SendCancellation(meetingId, New String() {lGetCounselorEmail1})
' Something very weird here. Running this code through the debugger works fine. Running without causes exchange to return 500 - Internal Server Error.
Threading.Thread.Sleep(500)
End If
x.Add(folder)
If Not String.IsNullOrEmpty(newAssignedTo) Then x.Add(GetCounselorEmail(newAssignedTo, transaction))
x.RemoveAll(AddressOf String.IsNullOrEmpty)
If x.Count > 0 Then
If Not Common.Exchange.UpdateMeetingAttendees(meetingId, x.ToArray()) Then
Throw New Exception("Failure during update of calendar")
End If
End If
End Sub
...but a lot of the implementation details are hidden here, as I wrote a set of classes to interface with Exchange WebDAV.
Ended up sticking with the Sleep and calling it a day.
My 'belief' is that I was erroneous in thinking that a WebRequest/WebResponse combo sent to Exchange through WebDav was an atomic operation.

How to diagnose "the operation has timed out" HttpException

I am calling 5 external servers to retrieve XML-based data for each request for a particular webpage on my IIS 6 server. Present volume is between 3-5 incoming requests per second, meaning 15-20 outgoing requests per second.
99% of the outgoing requests from my server (the client) to the external servers (the server) work OK but about 100-200 per day end up with a "The operation has timed out" exception.
This suggests I have a resource problem on my server - some shortage of sockets, ports etc or a thread lock but the problem with this theory is that the failures are entirely random - there are not a number of requests in a row that all fail - and two of the external servers account for the majority of the failures.
My question is how can I further diagnose these exceptions to determine if the problem is on my end (the client) or on the other end (the servers)?
The volume of requests precludes putting an analyzer on the wire - it would be very difficult to capture these few exceptions. I have reset CONNECTIONS and THREADS in my machine.config and the basic code looks like:
Dim hRequest As HttpWebRequest
Dim responseTime As String
Dim objWatch As New Stopwatch
Try
' calculate time it takes to process transaction
objWatch.Start()
hRequest = System.Net.WebRequest.Create(url)
' set some defaults
hRequest.Timeout = 5000
hRequest.ReadWriteTimeout = 10000
hRequest.KeepAlive = False ' to prevent open HTTP connection leak
hRequest.SendChunked = False
hRequest.AllowAutoRedirect = True
hRequest.MaximumAutomaticRedirections = 3
hRequest.Accept = "text/xml"
hRequest.Proxy = Nothing 'do not waste time searching for a proxy
hRequest.ServicePoint.Expect100Continue = False
Dim feed As New XDocument()
' use *Using* to auto close connections
Using hResponse As HttpWebResponse = DirectCast(hRequest.GetResponse(), HttpWebResponse)
Using reader As XmlReader = XmlReader.Create(hResponse.GetResponseStream())
feed = XDocument.Load(reader)
reader.Close()
End Using
hResponse.Close()
End Using
objWatch.Stop()
' Work here with returned contents in "feed" document
Return XXX' some results here
Catch ex As Exception
objWatch.Stop()
hRequest.Abort()
Return Nothing
End Try
Any suggestions?
By default, HttpWebRequest limits you to 2 connections per HTTP/1.1 server. So, if your requests take time to complete, and you have incoming requests queuing up on the server, you will run out of connection and thus get timeouts.
You should change the max outgoing connections on ServicePointManager.
ServicePointManager.DefaultConnectionLimit = 20 // or some big value.
You said that you are doing 5 outgoing request for each incoming request to the ASP page. Is that 5 different servers, or the same server?
DO you wait for the previous request to complete, before issuing the next one? Is the timeout happening while it is waiting for a connection, or during the request/response?
If the timeout is happening during the request/response then it means that the target server is under stress. The only way to find out if this is the case, is to run wireshark/netmon on one of the machines, and look at the network trace to see if the request from the app is even making it through to the server, and if it is, whether the target server is responding within the given timeout.
If this is a thread starvation issue, then one of the ways to diagnose it is to attach windbg.exe debugger to w3wp.exe process, when you start getting timeout. Then load the sos.dll debugging extension. And run the !threads command, followed by !threadpool command. It will show you how many Worker threads and completion port threads are utilized/remaining. If the #completionport threads or worker threads are low, then that will contribute to the timeout.
Alternatively, you can monitor ASP.NET and System.net perf counters. See if the ASP.NET request queue is increasing monotonically - this might indicate that your outgoing requests are not completing fast enough.
Sorry, there are no easy answers here. THere is a lot of avenues you will need to explore. If I were you, I would start off by attaching windbg.exe to w3wp when you start getting timeouts and do what I described earlier.