I want to get current internet ip address in vb.net. I don't want localhost ip address. like as (http://www.ipchicken.com/ website return ip address)
I understand what you are wanting is the IP address as you appear on the internet and NOT your internal network IP. I've got some code somewhere I'll dig out for you but it basically comprised of this (from memory):
Create a WebRequest and WebResponse object
Request a webpage (using WebRequest) that shows your IP (such as IP Chicken) and capture the response in the WebResponse object
Parse the response using regular expressions to collect your IP
Like I say I'll try and dig out the code but this should be more than enough information for you to work on :-)
Something like this should get your current public IP.
Public Class Form1
Private Sub Form1_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
AddHandler wb.DocumentCompleted, AddressOf wb_DocumentCompleted
End Sub
Public WithEvents wb As New WebBrowser
'before using wb add
'AddHandler wb.DocumentCompleted, AddressOf wb_DocumentCompleted
Private Sub GetPubIP()
Try
'the site returns a string like "Current IP Address: 69.59.196.211"
wb.Navigate(New Uri("http://checkip.dyndns.org"))
Catch ex As Exception
'add error checking
End Try
End Sub
Private Sub wb_DocumentCompleted(ByVal sender As Object, _
ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
'parse the reply
Dim parts() As String = wb.Document.Body.InnerText.Split(":"c)
Debug.WriteLine(parts(1).Trim)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
GetPubIP()
End Sub
End Class
Here's what you're looking for. I wrote a simple PHP script to return the IP address when called, then wrote this VB.Net code to call it at any time:
Public Function jnWhatIsMyExternalIP() As String
Dim strURL As String = "http://www.mycompanywebsite/jnNetworkTools/jnCheckIP.php"
Dim Request As System.Net.WebRequest = System.Net.WebRequest.Create(strURL)
Dim Response As System.Net.WebResponse = Request.GetResponse()
Dim Reader As New System.IO.StreamReader(Response.GetResponseStream())
Dim strMyIP As String = Reader.ReadToEnd()
Return strMyIP
End Function
Here's the PHP code that is in jnCheckIP.php:
<?php
echo $_SERVER['REMOTE_ADDR'];
?>
Calling the VB.Net function causes the users machine to call the PHP script on your server which then returns the users IP address.
You can know real ip address only if your host (pc) have static internet ip address, not like 194.x.x.x or 10.x.x.x and other http://en.wikipedia.org/wiki/Private_network
Otherwise try to send http request to service like www.ipchicken.com or other http://www.google.ru/search?hl=en&q=my+ip+address to know your ip address
This should do the trick:
http://www.vbdotnetheaven.com/UploadFile/prvn_131971/ipvb11162005073000AM/ipvb.aspx
Function GetIP() As String
Dim IP As New WebClient
Return IP.DownloadString("http://icanhazip.com/")
End Function
Related
How do I detect live IP Changes?
Example:
My ip without VPN: 3.3.3.3, whenever I connect to vpn my ip changes to 5.5.5.5.
My question is: How do I detect the IP has changed when the form is running?
I have tried:
Private Sub Timer4_Tick(sender As Object, e As EventArgs) Handles Timer4.Tick
Dim adapters As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
AddHandler NetworkChange.NetworkAddressChanged, AddressOf downloadip
Dim n As NetworkInterface
For Each n In adapters
Timer4.Stop()
Msgbox("IP Changed")
Next n
End Sub
Try checking your IP on an external website
for example:
Public Sub GetExternalIp()
Try
Dim WithEvents IPBrowser As New WebBrowser
IPBrowser.Visible = False
Me.Controls.Add(IPBrowser)
IpBrowser.Navigate("http://seemyip.com/onyoursite.php")
Catch
Label2.Text = "failed to get external IP"
End Try
End Sub
'then, put this OnNavigatingEvent
If IpBrowser.Document.All("ip").GetAttribute("value") IsNot Nothing Then
MyExtIp = IpBrowser.Document.All("ip").GetAttribute("value")
Else
MessageBox.Show("Can't find your IP")
End If
i am trying to establish connection between calamp lmu (gps tracking device) and my server.
i am using following code to send and receive data.
i am using timer1 to receive data from device
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Try
Dim receiveBytes As [Byte]() = receivingUdpClient.Receive(remoteEP)
Dim returnData As String = BitConverter.ToString(receiveBytes)
txtLog.Text &= returnData.ToString & vbCrLf
Dim rep As New IPEndPoint(remoteEP.Address, C_DEVICE_LISTNING_PORT)
sktSocket = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
sktSocket.Connect(remoteEP.Address, 20510)
sktSocket.SendTimeout = 100
'Dim udc As New UdpClient
'udc.Send(sendBytes, sendBytes.Length, rep)
'receivingUdpClient.Client.Send(sendBytes)
Catch ex As Exception
End Try
End Sub
following two variables are class level:
Dim remoteEP As New IPEndPoint(IPAddress.Any, 0)
Dim sktSocket As Socket
i am using following code to send data to device:
Private Sub butSend_Click(sender As Object, e As EventArgs) Handles butSend.Click
Dim sendBytes() As Byte = Encoding.ASCII.GetBytes(txtCommand.Text)
sktSocket.Send(sendBytes)
End Sub
my code to receive data works fine. when device sends data timer1 displays it in a textbox. But when i send data to the ip address returned by receivingUdpClient.Receive, it does not reach to the device. however wireshark shows that data has been sent.
any help will be appriciated.
i solved my problem myself. actually nothing was wrong in the code. actually i was connecting the device using forwarded port. it was hindering inward traffic from device to my system. Assigning static ip direct to my system solved the problem.
So I'm trying to make a very simple system to send messages from a client to a server (and later on from server to client as well, but baby steps first). I'm not sure exactly how to use UDPClient to send and receive messages (especially to receive them), mostly because I don't have anything triggering the ReceiveMessage() function and I'm not sure what would.
Source Code is at this link, go to File>Download. It is already built if you want to just run the exe.
So my question is basically: How can I easily use UDPClient, how can I get this system to work and what are some tips for executing this kind of connection? Anything I should watch out for (threading, issues with code,etc)?
Source.
You need first need to set up two UdpClients. One client for listening and the other for sending data. (You'll also need to pick a free/unused port number and know the IP address of your target - the machine you want to send data to.)
To set up the receiver,
Instantiate your UdpClient variable with the port number you chose earlier,
Create a new thread to avoid blocking while receiving data,
Loop over the client's receive method for as long as you want to receive data (the loop's execution should be within the new thread),
When you receive one lot of data (called a "packet") you may need to convert the byte array to something more meaningful,
Create a way to exit the loop when you want to finish receiving data.
To set up the sender,
Instantiate your UdpClient variable with the port number you chose earlier (you may want to enable the ability to send broadcast packets. This allows you to send data to all listeners on your LAN),
When you need to transmit data, convert the data to a byte array and then call Send().
I'd suggest that you have a quick skim read through this.
Here's some code to get you started off...
'''''''''''''''''''''''Set up variables''''''''''''''''''''
Private Const port As Integer = 9653 'Port number to send/recieve data on
Private Const broadcastAddress As String = "255.255.255.255" 'Sends data to all LOCAL listening clients, to send data over WAN you'll need to enter a public (external) IP address of the other client
Private receivingClient As UdpClient 'Client for handling incoming data
Private sendingClient As UdpClient 'Client for sending data
Private receivingThread As Thread 'Create a separate thread to listen for incoming data, helps to prevent the form from freezing up
Private closing As Boolean = False 'Used to close clients if form is closing
''''''''''''''''''''Initialize listening & sending subs'''''''''''''''''
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
InitializeSender() 'Initializes startup of sender client
InitializeReceiver() 'Starts listening for incoming data
End Sub
''''''''''''''''''''Setup sender client'''''''''''''''''
Private Sub InitializeSender()
sendingClient = New UdpClient(broadcastAddress, port)
sendingClient.EnableBroadcast = True
End Sub
'''''''''''''''''''''Setup receiving client'''''''''''''
Private Sub InitializeReceiver()
receivingClient = New UdpClient(port)
Dim start As ThreadStart = New ThreadStart(AddressOf Receiver)
receivingThread = New Thread(start)
receivingThread.IsBackground = True
receivingThread.Start()
End Sub
'''''''''''''''''''Send data if send button is clicked'''''''''''''''''''
Private Sub sendBut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sendBut.Click
Dim toSend As String = tbSend.Text 'tbSend is a textbox, replace it with whatever you want to send as a string
Dim data() As Byte = Encoding.ASCII.GetBytes(toSend)'Convert string to bytes
sendingClient.Send(data, data.Length) 'Send bytes
End Sub
'''''''''''''''''''''Start receiving loop'''''''''''''''''''''''
Private Sub Receiver()
Dim endPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, port) 'Listen for incoming data from any IP address on the specified port (I personally select 9653)
While (True) 'Setup an infinite loop
Dim data() As Byte 'Buffer for storing incoming bytes
data = receivingClient.Receive(endPoint) 'Receive incoming bytes
Dim message As String = Encoding.ASCII.GetString(data) 'Convert bytes back to string
If closing = True Then 'Exit sub if form is closing
Exit Sub
End If
End While
End Sub
'''''''''''''''''''Close clients if form closes''''''''''''''''''
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
closing = True 'Tells receiving loop to close
receivingClient.Close()
sendingClient.Close()
End Sub
Here are a few other exmples: Here, here, here and here.
Imports System.Threading
Shared client As UdpClient
Shared receivePoint As IPEndPoint
client = New UdpClient(2828) 'Port
receivePoint = New IPEndPoint(New IPAddress(0), 0)
Dim readThread As Thread = New Thread(New ThreadStart(AddressOf WaitForPackets))
readThread.Start()
Public Shared Sub WaitForPackets()
While True
Dim data As Byte() = client.Receive(receivePoint)
Console.WriteLine("=" + System.Text.Encoding.ASCII.GetString(data))
End While
End Sub
I am currently developing a file sharing application using asynchronous communication in VB.Net. I successfully coded a simple connection between the client and the server. But, I am currently having a bad time doing the disconnection sub routine for both the client and the server. I'm currently stuck in this problem for a couple of days already and have decided to seek help here because I can't find any good ways to do the disconnection thing.
Here's my code:
Server Application
Private Sub FileSharingInitialize()
ServerSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim EndPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, 7777)
ServerSocket.Bind(EndPoint)
ServerSocket.Listen(0)
End Sub
Private Sub FileSharingOnAccept(ByVal AsyncResult As IAsyncResult)
ClientSocket = ServerSocket.EndAccept(AsyncResult)
FileSharingAddClient(ClientSocket)
ClientSocket.BeginReceive(ByteData, 0, ByteData.Length, SocketFlags.None, New AsyncCallback(AddressOf FileSharingOnReceive), ClientSocket)
End Sub
Delegate Sub _FileSharingAddClient(ByVal Client As Socket)
Private Sub FileSharingAddClient(ByVal Client As Socket)
If InvokeRequired Then
Invoke(New _FileSharingAddClient(AddressOf FileSharingAddClient), Client)
Exit Sub
End If
lvConnectedClients.Items.Add("")
lvConnectedClients.Items(lvConnectedClients.Items.Count - 1).SubItems.Add(Client.LocalEndPoint.ToString)
End Sub
Private Sub FileSharingOnReceive(ByVal AsyncResult As IAsyncResult)
Dim Client As Socket = CType(AsyncResult.AsyncState, Socket)
Client.EndReceive(AsyncResult)
Dim ByteReceived As Byte() = ByteData
Dim LogMessage As String = System.Text.Encoding.ASCII.GetString(ByteReceived)
ReadLogMessage(LogMessage)
End Sub
Delegate Sub _ReadLogMessage(ByVal LogMessage As String)
Private Sub ReadLogMessage(ByVal LogMessage As String)
If InvokeRequired Then
Invoke(New _ReadLogMessage(AddressOf ReadLogMessage), LogMessage)
Exit Sub
End If
DisplayLogMessage(LogMessage)
End Sub
Private Sub DisplayLogMessage(ByVal Log As String)
Dim TimeStamp As String = "[" & DateAndTime.Now.ToString("hh:mm:ss tt dddd, dd MMMM yyyy") & "]: "
Dim LogMessage As String = ""
If txtLog.Text > "" Then
LogMessage = Chr(10) & Chr(13)
End If
LogMessage &= TimeStamp
LogMessage &= Log
txtLog.SelectionStart = Len(txtLog.Text)
txtLog.SelectedText = LogMessage
End Sub
Private Sub frmMain_Load(sender As Object, e As System.EventArgs) Handles Me.Load
FileSharingInitialize()
End Sub
Private Sub btnStart_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles btnStart.MouseClick
ServerSocket.BeginAccept(New AsyncCallback(AddressOf FileSharingOnAccept), Nothing)
DisplayLogMessage("Server started." & Environment.NewLine)
End Sub
On the server part, when I press the stop button, I want to disconnect all the clients from the server. I have tried this code in my start button but it doesn't work. I'm receiving an error that says the socket is not connected. I'm thinking that maybe I am disconnecting the wrong socket since I have also a socket named ClientSocket in the server application. Or maybe, I should do it with a loop to disconnect the clients? What do you think?
Private Sub btnStop_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles btnStop.MouseClick
ServerSocket.Shutdown(SocketShutdown.Both)
ServerSocket.Close()
ServerSocket = Nothing
End Sub
Client Application
Private Sub btnConnect_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles btnConnect.MouseClick
ClientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim Address As IPAddress = IPAddress.Parse(frmNetworkSettings.txtServerIPAddress.Text)
Dim Endpoint As IPEndPoint = New IPEndPoint(Address, CInt(frmNetworkSettings.txtFileSharingPort.Text))
ClientSocket.BeginConnect(Endpoint, New AsyncCallback(AddressOf FileSharingOnConnect), Nothing)
SendLogMessage(Username & " is connected." & Environment.NewLine, ClientSocket)
End Sub
Private Sub FileSharingOnConnect(ByVal AsyncResult As IAsyncResult)
ClientSocket.EndConnect(AsyncResult)
End Sub
Private Sub SendLogMessage(ByVal LogMessage As String, ByVal Client As Socket)
Dim SendByteData As Byte() = System.Text.Encoding.ASCII.GetBytes(LogMessage)
Client.BeginSend(SendByteData, 0, SendByteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnSendLogMessage), Client)
End Sub
Private Sub OnSendLogMessage(ByVal AsyncResult As IAsyncResult)
Dim Client As Socket = CType(AsyncResult.AsyncState, Socket)
Client.EndSend(AsyncResult)
End Sub
The problem on the client part is the same on the server. The code to disconnect the client from the server doesn't work. It doesn't send any logs to the server after I press the disconnect button, even when I reconnect afterwards. It seems that the socket has been disposed? If so, how can I prevent it from doing that and reuse the socket when I try to reconnect? Another thing, is that when I press the connect button without starting the server and afterwards start the server, a log is sent to the server that the client connected. It seems that the problem is on the listen method of the server. I don't want that to happen, I just want an exception or something that will alert the user that the client is not connected to the server and do not send a log message to the server afterwards the client connects. I don't really know, but do you think that if I set the backlog of the listen method to zero will prevent that from happening?
Thanks in advance!
Better way to do this is to implement flag system. When one client or server want to disconnect from other send disconnect flag to other end so on other end you code will understand disconnection
I converted a project from html into aspx
Issue is, all the extension got changed.
e.g. "www.example.com\index.html" Changed to "www.example.com\index.aspx"
which give problem to SEO's.
so now when i search for the web i get the link as www.example.com\index.html and if i try to go in it, it give me the error of 404 file not found.
I tried couple of methods for URL-ReWriting, it works fine at local side, but it fails at server side.
Both i tried in Global.asax
1.
Protected Overloads Sub Application_BeginRequest(ByVal sender As Object, ByVal e As System.EventArgs)
Dim CurrentPath As String = Request.Path.ToLower()
Dim strPageName As String = CurrentPath.Substring(CurrentPath.LastIndexOf("/") + 1, (CurrentPath.LastIndexOf(".") - CurrentPath.LastIndexOf("/")) + 4)
If strPageName.EndsWith(".html") Then
Select Case strPageName
Case "index.html"
RewriteUrl(CurrentPath)
End Select
End If
End Sub
Protected Sub RewriteUrl(ByVal URL As String)
Dim CurrentPath As String = URL
CurrentPath = CurrentPath.Replace(".html", ".aspx")
Dim MyContext As HttpContext = HttpContext.Current
MyContext.RewritePath(CurrentPath)
End Sub
2.
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
RegisterRoutes(RouteTable.Routes)
End Sub
Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.Add("Index", New Route _
( _
"index.html", New CustomRouteHandler("~/index.aspx") _
))
End Sub
Do you have control of the web server? What you most likely need SEO-wise is to create a permanent (301) URL redirect which you can do at the web server level...often in the server settings, or in a script file.
See: http://en.wikipedia.org/wiki/URL_redirection
I realize this doesn't answer your question directly, but if all you are trying to do is get the search results to the correct new page, this is the best way to do it.