How to get my real IP using vb.net? - vb.net

How to get my real IP using vb.net?

If you are running in ASP.NET, then use the HttpRequest.UserHostAddress property:
Dim ip as string
ip = Request.UserHostAddress()

Create php script. Save it as realip.php
<?php
echo $this->getRealIpAddr();
function getRealIpAddr()
{
$ip = "";
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
?>
In your VB.net project create a module.
Declare the imports section at the very top
Imports System.Net
Imports System.IO
And create your function:
Public Function GetIP() As String
Dim uri_val As New Uri("http://yourdomain.com/realip.php")
Dim request As HttpWebRequest = HttpWebRequest.Create(uri_val)
request.Method = WebRequestMethods.Http.Get
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As New StreamReader(response.GetResponseStream())
Dim myIP As String = reader.ReadToEnd()
response.Close()
Return myIP
End Function
Now anywhere in your code you can issue
Dim myIP as String = GetIP()
as use the value from there as you wish.

As you can see here (how and why), the best way to get the client IP is:
Dim clientIP As String
Dim ip As String = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If Not String.IsNullOrEmpty(ip) Then
Dim ipRange As String() = ip.Trim().Split(","C)
Dim le As Integer = ipRange.Length - 1
clientIP = ipRange(le)
Else
clientIP = Request.ServerVariables("REMOTE_ADDR")
End If

Dim req As HttpWebRequest = WebRequest.Create("http://whatismyip.com/automation/n09230945.asp")
Dim res As HttpWebResponse = req.GetResponse()
Dim Stream As Stream = res.GetResponseStream()
Dim sr As StreamReader = New StreamReader(Stream)
MsgBox(sr.ReadToEnd())

Related

Vb.net webapi file download troubles

We've been using an IIS filehandler to download files that are stored in a database such as PowerPoint. Now we're trying to switch to webapi. File uploads are working fine but downloads are not.
Using the filehandler the url is like: http://localhost:57851/docmgr?id=6202 which returns a valid file with the following info from Fiddler:
Using the same code in a webapi controller having a url of: http://localhost:57851/webapi/file/GetFile?id=6202 returns a file with additional bytes added. Fiddler data:
Note the change in content-type as well even though the content-type is expressly set to "application/vnd.ms-powerpoint".
I must be missing something....
Here is the controller code:
<HttpGet>
Public Function GetFile()
Dim dbConn As New SqlConnection(DigsConnStr)
Dim dbCmd As New SqlCommand
Dim dbRdr As SqlDataReader
Dim id As String = HttpContext.Current.Request.QueryString("id")
Dim bytes As Byte()
Dim contentType As String
Dim fileName As String
Dim fileExt As String
Try
dbConn.Open()
dbCmd.Connection = dbConn
dbCmd.CommandText = "GET_FileForDownload"
dbCmd.CommandType = CommandType.StoredProcedure
dbCmd.Parameters.AddWithValue("#VirtualFileRecID", id)
dbRdr = dbCmd.ExecuteReader
dbRdr.Read()
contentType = dbRdr("ContentType")
bytes = dbRdr("FileBytes")
fileExt = dbRdr("FileExtension")
If contentType <> "" Then
fileName = dbRdr("Title") & fileExt
HttpContext.Current.Response.ContentType = contentType
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" & fileName)
HttpContext.Current.Response.BinaryWrite(bytes)
'HttpContext.Current.Response.Flush()
End If
dbConn.Close()
Catch ex As Exception
dbConn.Close()
Finally
If Not (dbConn Is Nothing) Then dbConn.Close()
End Try
End Function
WebAPI is going to wrap your response in XML (or whatever formatter you have in your webapiconfig class)
You really shouldn't access the response stream directly with WebAPI but you can return a HttpResponseMessage object with the file stream
Check this out
<HTTPGET>
Public Function GetFile(FileID as Integer) As HttpResponseMessage
Dim path = "C:\Temp\test.exe"
Dim result As New HttpResponseMessage(HttpStatusCode.OK)
Dim stream = New FileStream(path, FileMode.Open)
result.Content = New StreamContent(stream)
result.Content.Headers.ContentType = New MediaTypeHeaderValue("application/octet-stream")
Return result
End Function
Then you should really access it like this: http://localhost:57851/docmgr/6202

Authenticating to Web Service VB.Net

Hi I am trying to Authenticate to my web service and missing something..
My Service reference is called - MBSDKServiceLD
My Web Reference is called - LANDeskMBSDK
I have these connected in Visual Studio 2013 And are resolving methods in the code
Here is my code for the authentication but its not complete..
Option Explicit On
Imports System.Net
Dim objFSO As Object
Dim objExec As Object
Dim objNetwork As Object
Dim strComputer As String
Dim strUser As String
Dim User As String
Dim Password As String
Dim Domain As String
Dim URL As String
Dim Cred As String
Dim strTaskName As String
Dim strPackageName As String
Dim strDeliveryMethod As String
Dim strCustomGroup As String
Dim boolStartNow As Boolean
Dim WakeUpMachines As Boolean
Dim boolCommonTask As Boolean
Dim strAutoSync As String
Dim TaskID As String
Dim strConnection As New System.Data.SqlClient.SqlConnection
Dim LDWebService
Dim intTaskID As String
Dim LDService As Object
Dim strDeviceName As String
Sub RunLANDeskTask(ByVal sender As Object, ByVal LDService As MBSDKServiceLD.MBSDKSoap)
End Sub
Sub CreateTask
User = "username1"
Password = "password1"
Domain = "domain1"
URL = "http://myserver/MBSDKService/MsgSDK.asmx?WSDL"
Dim MyCredentails As New System.Net.CredentialCache()
Dim NetCred As New System.Net.NetworkCredential(User, Password, Domain)
MyCredentails.Add(New Uri(URL), "Basic", NetCred)
strPackageName = "Adobe Acrobat XI PRO"
strDeliveryMethod = "Standard push distribution"
Dim strTargetDevice As String
strTargetDevice = Nothing
strTaskName = strPackageName & " - " & DateTime.Now & " -Provisioning Task for" & " " & strComputer
Try
RunLANDeskTask(LANDeskMBSDK, LDService.CreateTask(strTaskName, strDeliveryMethod, strPackageName, False, False, strAutoSync).TaskID)
Catch ex As Exception
MsgBox("Error creating task")
End Try
End Sub
What comes after this part or have i got this totally wrong?
When I type LDService. I see all the methods so I am connecting to the reference in VS but not authenticating.
It should really be as simple as this (sorry it's in c#):
MyWebService svc = new MyWebService();
svc.Credentials = new System.Net.NetworkCredential(UserID, pwd);
bool result = svc.MyWebMethod();
The following might be helpful:
This is quite old, but the comments are good.
I've just found the following on MSDN, which looks like what you want:
localhost.Sample svc = new localhost.Sample();
try {
CredentialCache credCache = new CredentialCache();
NetworkCredential netCred =
new NetworkCredential( "Example", "Test$123", "sseely2" );
credCache.Add( new Uri(svc.Url), "Basic", netCred );
svc.Credentials = credCache;
Ok i got this working... But i have to run the code under an account that can access the Web service -
Dim URL As String = "http://server/MBSDKService/MsgSDK.asmx?WSDL"
Dim myService As New LANDeskMBDSK.MBSDK
myService.Url = URL
Dim CredCache As New System.Net.CredentialCache
CredCache.Add(New Uri(myService.Url), "Basic", Cred)
myService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials

REST WebService: how to get zip file from web service to a client

I'm trying to create a function to download a zip file made ​​available from a REST WebService with a client that calls the Web Service(both written in VB.Net).
WebService side I have the following code:
Public Function DownloadZipFile(filename As String) As Stream Implements ILiveUpdateWS.DownloadZipFile
WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt"
Dim f As New FileStream(DESTINATION_PATH_ZIP_FILE + "Upgrade_Package.zip",FileMode.Open)
Dim length As Integer = CType(f.Length, Integer)
WebOperationContext.Current.OutgoingResponse.ContentLength = length
Dim buffer As Byte() = New Byte(length) {}
Dim sum As Integer = 0
Dim count As Integer
While ((count = f.Read(buffer, sum, length - sum)) > 0)
sum += count
End While
f.Close()
Dim mimeType = ""
WebOperationContext.Current.OutgoingResponse.ContentType = mimeType
Return New MemoryStream(buffer)
End Function
Client side I have the following code:
sUri = "http://localhost:35299/LiveUpdateWS/Download?" & "piv"
....
Dim req As HttpWebRequest = WebRequest.Create(sUri.ToString())
req.Method = "GET"
req.KeepAlive = False
Dim response As HttpWebResponse = req.GetResponse()
Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)
Dim stIn As IO.StreamReader = New IO.StreamReader(response.GetResponseStream())
Response has ContentLenght = 242699, so seems to receive the stream, but StIn seems to be empty. What is the best solution to solve the problem?
I think you've forgot to read from the StreamReader to the file.
Dim inSaveFile As String = "C:\stream\test.doc"
If Dir(inSaveFile) <> vbNullString Then
Kill(inSaveFile)
End If
Dim swFile As System.IO.StreamWriter
Dim fs As System.IO.FileStream = System.IO.File.Open(inSaveFile, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write)
swFile = New System.IO.StreamWriter(fs, System.Text.Encoding.Default)
Dim response1 As System.Net.HttpWebResponse = req.GetResponse()
Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)
Dim stIn As IO.StreamReader = New IO.StreamReader(response1.GetResponseStream(), encoding:=System.Text.Encoding.Default)
swFile.WriteLine(stIn.ReadToEnd)
swFile.Close()
fs.Close()

Is there any way to optimize performance of reading stream?

I'm requesting remote SOAP web-service but all operation (from click search button to render interface with answer) took almost two minutes, it's too long. So I wonder if there any possible way to improve performance of the current code.
Operation that parse xml and read data to database working quite well, problem only about reading answer from stream.
Public Shared Function CallWebService(ByVal an As String, ByVal xmlcommand As String) As String
Dim _url = "http://testapi.interface-xml.com/appservices/ws/FrontendService"
Dim soapEnvelopeXml As XmlDocument = CreateSoapEnvelope(xmlcommand)
Dim webRequest As HttpWebRequest = CreateWebRequest(_url, an)
webRequest.Proxy = System.Net.WebRequest.DefaultWebProxy
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest)
Dim asyncResult As IAsyncResult = webRequest.BeginGetResponse(Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Dim soapResult As String
Using webResponse As WebResponse = webRequest.EndGetResponse(asyncResult)
Using bs As New BufferedStream(webResponse.GetResponseStream())
Using rd As New StreamReader(bs)
soapResult = rd.ReadLine()
Return soapResult
End Using
End Using
End Using
End Function
Here is solution!
Public Shared Function CallWebService(ByVal an As String, ByVal xmlcommand As String) As String
Dim _url = "http://testapi.interface-xml.com/appservices/ws/FrontendService"
Dim soapEnvelopeXml As XmlDocument = CreateSoapEnvelope(xmlcommand)
Dim webRequest As HttpWebRequest = CreateWebRequest(_url, an)
webRequest.Proxy = System.Net.WebRequest.DefaultWebProxy
webRequest.Headers.Add("Accept-Encoding", "gzip, deflate")
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest)
Dim asyncResult As IAsyncResult = webRequest.BeginGetResponse(Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Dim soapResult As String
Using webResponse As WebResponse = webRequest.EndGetResponse(asyncResult)
Using bs As New BufferedStream(webResponse.GetResponseStream())
Using gz As New GZipStream(bs, CompressionMode.Decompress)
Using rd As New StreamReader(gz)
soapResult = rd.ReadLine()
Return soapResult
End Using
End Using
End Using
End Using
End Function

How to post XML document to HTTP with VB.Net

I'm looking for help with posting my XML document to a url in VB.NET. Here's what I have so far ...
Public Shared xml As New System.Xml.XmlDocument()
Public Shared Sub Main()
Dim root As XmlElement
root = xml.CreateElement("root")
xml.AppendChild(root)
Dim username As XmlElement
username = xml.CreateElement("username")
username.InnerText = _username
root.AppendChild(username)
xml.Save(Console.Out)
Dim url = "https://mydomain.com"
Dim req As WebRequest = WebRequest.Create(url)
req.Method = "POST"
req.ContentType = "application/xml"
req.Headers.Add("Custom: API_Method")
Console.WriteLine(req.Headers.ToString())
This is where things go awry:
I want to post the xml, and then print the results to console.
Dim newStream As Stream = req.GetRequestStream()
xml.Save(newStream)
Dim response As WebResponse = req.GetResponse()
Console.WriteLine(response.ToString())
End Sub
This is essentially what I was after:
xml.Save(req.GetRequestStream())
If you don't want to take care about the length, it is also possible to use the WebClient.UploadData method.
I adapted your snippet slightly in this way.
Imports System.Xml
Imports System.Net
Imports System.IO
Public Module Module1
Public xml As New System.Xml.XmlDocument()
Public Sub Main()
Dim root As XmlElement
root = xml.CreateElement("root")
xml.AppendChild(root)
Dim username As XmlElement
username = xml.CreateElement("username")
username.InnerText = "user1"
root.AppendChild(username)
Dim url = "http://mydomain.com"
Dim client As New WebClient
client.Headers.Add("Content-Type", "application/xml")
client.Headers.Add("Custom: API_Method")
Dim sentXml As Byte() = System.Text.Encoding.ASCII.GetBytes(xml.OuterXml)
Dim response As Byte() = client.UploadData(url, "POST", sentXml)
Console.WriteLine(response.ToString())
End Sub
End Module