Get IP Addresses of 6 devices using MAC addresses using VB.NET - vb.net

How do I modify my code to populate a listbox of IP addresses if I know 6 devices MAC addresses?
I am using VB.net to show me my current IP and MAC address but I want to change it to add to a ListBox to show 6 devices on the same network using their MAC addresses. Since we cannot modify the DHCP server, we just want a simple way to show each device's IP address using their known Mac addresses. I will add the MAC addresses in code. but Just want to have the listbox populate on startup of the app.
Existing Code:
Imports System.Net
Imports System.Runtime.InteropServices
Imports System.ComponentModel
Imports System.IO
Imports System.Net.NetworkInformation
Public Class Form1
Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
Dim mac As String
mac = GetMacAddress()
Label1.Text = mac
End Sub
Function GetMacAddress()
Dim nics() As NetworkInterface = NetworkInterface.GetAllNetworkInterfaces()
Return nics(0).GetPhysicalAddress.ToString
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Close()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GetIPv4Address()
End Sub
Private Function GetIPv4Address() As String
GetIPv4Address = String.Empty
Dim strHostName As String = System.Net.Dns.GetHostName()
Dim iphe As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(strHostName)
For Each ipheal As System.Net.IPAddress In iphe.AddressList
If ipheal.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
GetIPv4Address = ipheal.ToString()
Label2.Text = "IP Address: " & ipheal.ToString
End If
Next
End Function
End Class
Thanks in advance!

Updated Answer - After some more digging, I found untweaked version of the code below here and tweaked it a bit.
What you end up with is a list of IpInfo structures. Each of these objects has the self-explanatory properties of IpAddress, MacAddress and HostName. You can iterate through the list and IP addresses the matching mac addresses to your listbox.
You may need to tweak the Thread.Sleep interval to make sure that you get all the results, but I hope this new answer sorts you out.
If it does, I would suggest removing the comments about the code not working so that they don't confuse others looking at this answer.
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Public Class Form1
Structure IpInfo
Dim IpAddress As String
Dim HostName As String
Dim MacAddress As String
End Structure
Dim connectedIPAddresses As New List(Of IpInfo)
Private Shared Function NetworkGateway() As String
Dim ip As String = Nothing
For Each f As NetworkInterface In NetworkInterface.GetAllNetworkInterfaces()
If f.OperationalStatus = OperationalStatus.Up Then
For Each d As GatewayIPAddressInformation In f.GetIPProperties().GatewayAddresses
ip = d.Address.ToString()
Next
End If
Next
Return ip
End Function
Public Sub Ping_all()
Dim gate_ip As String = NetworkGateway()
Dim array As String() = gate_ip.Split("."c)
For i As Integer = 2 To 255
Dim ping_var As String = array(0) & "." & array(1) & "." & array(2) & "." & i.ToString
Ping(ping_var, 1, 1000)
Next
Task.WhenAll(taskList)
End Sub
Dim taskList As New List(Of Task)
Public Sub Ping(ByVal host As String, ByVal attempts As Integer, ByVal timeout As Integer)
For i As Integer = 0 To attempts - 1
taskList.Add(Task.Run(Sub()
Try
Dim ping As System.Net.NetworkInformation.Ping = New System.Net.NetworkInformation.Ping()
AddHandler ping.PingCompleted, AddressOf PingCompleted
ping.SendAsync(host, timeout, host)
Catch
End Try
End Sub))
Next
End Sub
Private Sub PingCompleted(ByVal sender As Object, ByVal e As PingCompletedEventArgs)
Dim ip As String = CStr(e.UserState)
If e.Reply IsNot Nothing AndAlso e.Reply.Status = IPStatus.Success Then
Dim hostname As String = GetHostName(ip)
Dim macaddres As String = GetMacAddress(ip)
Dim newIpAddress As IpInfo
newIpAddress.IpAddress = ip
newIpAddress.MacAddress = macaddres
newIpAddress.HostName = hostname
connectedIPAddresses.Add(newIpAddress)
Else
End If
End Sub
Public Function GetHostName(ByVal ipAddress As String) As String
Try
Dim entry As IPHostEntry = Dns.GetHostEntry(ipAddress)
If entry IsNot Nothing Then
Return entry.HostName
End If
Catch __unusedSocketException1__ As SocketException
End Try
Return Nothing
End Function
Public Function GetMacAddress(ByVal ipAddress As String) As String
Dim macAddress As String = String.Empty
Dim Process As System.Diagnostics.Process = New System.Diagnostics.Process()
Process.StartInfo.FileName = "arp"
Process.StartInfo.Arguments = "-a " & ipAddress
Process.StartInfo.UseShellExecute = False
Process.StartInfo.RedirectStandardOutput = True
Process.StartInfo.CreateNoWindow = True
Process.Start()
Dim strOutput As String = Process.StandardOutput.ReadToEnd()
Dim substrings As String() = strOutput.Split("-"c)
If substrings.Length >= 8 Then
macAddress = substrings(3).Substring(Math.Max(0, substrings(3).Length - 2)) & "-" & substrings(4) & "-" & substrings(5) & "-" & substrings(6) & "-" & substrings(7) & "-" + substrings(8).Substring(0, 2)
Return macAddress
Else
Return "OWN Machine"
End If
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Ping_all()
Threading.Thread.Sleep(10000)
For Each ip As IpInfo In connectedIPAddresses
ListBox1.Items.Add(ip.IpAddress)
Next
End Sub

Related

How to Get IP Addresses in LAN Network Using VB.Net

enter image description hereI want to get IP addresses in That are connected with LAN network. I seen a youtube tutorial Youtube Video Got the addresses but only last address show here in my dataGridView
I want to get all addresses in datagridviewlist using VB.Net
Maybe my english is bit lower but I need help
This is My Code
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strHost As String
Dim strIp As String
strHost = Dns.GetHostName()
strIp = Dns.GetHostByName(strHost).AddressList(0).ToString()
TxtForIp.Text = strIp
End Sub
Private Sub BgScanningForIps_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BgScanningForIps.DoWork
Dim ping As Ping
Dim addr As IPAddress
Dim pinRpl As PingReply
Dim host As IPHostEntry
Dim name As String
Thread.Sleep(500)
Parallel.For(0, 254, Sub(i, loopState)
ping = New Ping()
pinRpl = ping.Send(TxtForIp.Text + i.ToString())
Me.BeginInvoke(CType(Sub()
If pinRpl.Status = IPStatus.Success Then
Try
addr = IPAddress.Parse(TxtForIp.Text + i.ToString())
host = Dns.GetHostEntry(addr)
name = host.HostName
DataGridView1.Rows.Add()
Dim nRowIndex As Integer = DataGridView1.Rows.Count - 1
DataGridView1.Rows(nRowIndex).Cells(0).Value = TxtForIp.Text + i.ToString()
DataGridView1.Rows(nRowIndex).Cells(1).Value = name
DataGridView1.Rows(nRowIndex).Cells(2).Value = "active"
Catch ex As Exception
name = "?"
End Try
End If
End Sub, Action))
End Sub)
MessageBox.Show("Scanned")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BgScanningForIps.RunWorkerAsync()
End Sub
End Class

FOR statement conflicting with IF statement in VB

I am creating a fairly simple ping tool which shows in milliseconds how long the server took to respond. If the server does not respond, it shows as it responded in 0ms. I wanted to implement an If statement to write Server failed to respond in the ListBox rather than it replied in 0ms. The only problem with this is I have a chunk of code which need to be run outside the If but continues inside the If and involves using the line of code Next... This seems to cause the If statement to not recognise the End If and the End If to not recognise the If...
Here is my code:
For i As Integer = 0 To numberOfPings - 1
Dim ping As New Ping
Dim pingRe As PingReply = ping.Send(pingTarget)
If pingRe.RoundtripTime = 0 Then
Me.listboxPing.Items.Add("Server failed to respond...")
Else
Me.listboxPing.Items.Add("Response from " & pingTarget & " in " & pingRe.RoundtripTime.ToString() & "ms")
listboxPing.SelectedIndex = listboxPing.Items.Count - 1
listboxPing.SelectedIndex = -1
Application.DoEvents()
Threading.Thread.Sleep(500)
Next
Me.listboxPing.Items.Add("")
End If
Does anyone know of a way I could fix this/get around this issue?
Thanks,
If I were going to write code to ping an address and show the results it would look something like this.
Dim pingThrd As Threading.Thread
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If pingThrd Is Nothing OrElse pingThrd.ThreadState = Threading.ThreadState.Stopped Then
RichTextBox1.Clear()
pingThrd = New Threading.Thread(AddressOf PingIt)
pingThrd.IsBackground = True
pingThrd.Start("192.168.33.1")
End If
End Sub
Public Sub PingIt(pingTarget As Object)
Dim numberOfPings As Integer = 5
Dim pingT As String = DirectCast(pingTarget, String)
Dim pingTimeOut As Integer = 1000
Const dlyBetweenPing As Integer = 500
Dim dspStr As String
For i As Integer = 0 To numberOfPings - 1
Dim pingit As New Ping
Dim pingRe As PingReply = pingit.Send(pingT, pingTimeOut)
'check if success
If pingRe.Status = IPStatus.Success Then
dspStr = String.Format("Response from: {0} in {1}ms.", pingRe.Address, pingRe.RoundtripTime)
Else
dspStr = String.Format("{0} failed. Status: {1}", pingRe.Address, pingRe.Status)
End If
Me.BeginInvoke(Sub()
RichTextBox1.AppendText(dspStr)
RichTextBox1.AppendText(Environment.NewLine)
End Sub)
Threading.Thread.Sleep(dlyBetweenPing)
Next
End Sub
edit: Same basic code but allow thread to start with different address and count.
Structure PingWhat
Dim addr As String
Dim howmany As Integer
End Structure
Dim pingThrd As Threading.Thread
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If pingThrd Is Nothing OrElse pingThrd.ThreadState = Threading.ThreadState.Stopped Then
RichTextBox1.Clear()
'setup a thread to do the actual ping'ing
'this allows the UI to function
pingThrd = New Threading.Thread(AddressOf PingIt)
pingThrd.IsBackground = True
'setup address to ping and howmany times to ping it
Dim somePing As New PingWhat With {.addr = "192.168.33.1", .howmany = 3}
'start the thread
pingThrd.Start(somePing)
End If
End Sub
Public Sub PingIt(pingTarget As Object)
Dim pingT As PingWhat = DirectCast(pingTarget, PingWhat)
Dim pingTimeOut As Integer = 1000
Const dlyBetweenPing As Integer = 500
Dim dspStr As String
For i As Integer = 1 To pingT.howmany
Dim pingit As New Ping
Dim pingRe As PingReply = pingit.Send(pingT.addr, pingTimeOut)
'check if success
If pingRe.Status = IPStatus.Success Then
dspStr = String.Format("Response from: {0} in {1} ms.", pingRe.Address, pingRe.RoundtripTime)
Else
dspStr = String.Format("Ping Failed {0}. Status: {1}", pingT.addr, pingRe.Status)
End If
'update the UI
Me.BeginInvoke(Sub()
RichTextBox1.AppendText(dspStr)
RichTextBox1.AppendText(Environment.NewLine)
RichTextBox1.ScrollToCaret()
End Sub)
Threading.Thread.Sleep(dlyBetweenPing)
Next
Me.BeginInvoke(Sub()
RichTextBox1.AppendText("Done")
RichTextBox1.AppendText(Environment.NewLine)
RichTextBox1.ScrollToCaret()
End Sub)
End Sub
Is this what you're after?
For i As Integer = 0 To numberOfPings - 1
Dim ping As New Ping
Dim pingRe As PingReply = ping.Send(pingTarget)
If pingRe.RoundtripTime = 0 Then
Me.listboxPing.Items.Add("Server failed to respond...")
Else
Me.listboxPing.Items.Add("Response from " & pingTarget & " in " & pingRe.RoundtripTime.ToString() & "ms")
listboxPing.SelectedIndex = listboxPing.Items.Count - 1
listboxPing.SelectedIndex = -1
Application.DoEvents()
Threading.Thread.Sleep(500)
add = True
Exit For
End If
Next
If add Then Me.listboxPing.Items.Add("")
The If will change the scope, therefore, you need to use a variable to check whether it went into the Else part.
Of course, you need to close the first If before the Next.
#dbasnett This was the code I using before and it was absolutely perfect for what i needed EXCEPT if a ping failed it would just say (PingTarget) responded in 0ms which is not ideal. Ideally i would like it to say Server failed to respond... . Do you know a way in which this can be achieved by modifying my original code?
Imports System.Net.NetworkInformation
Imports System.Runtime.InteropServices
Public Class PingClient
Private Const EM_SETCUEBANNER As Integer = &H1501
<DllImport("user32.dll", CharSet:=CharSet.Auto)>
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As Integer, <MarshalAs(UnmanagedType.LPWStr)> ByVal lParam As String) As Int32
End Function
Private Sub SetCueText(ByVal control As Control, ByVal text As String)
SendMessage(control.Handle, EM_SETCUEBANNER, 0, text)
End Sub
Private Sub PingClient_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetCueText(textboxIP, "IP Address/Domain")
SetCueText(textboxPing, "No. Of Pings")
End Sub
Structure PingWhat
Dim addr As String
Dim howmany As Integer
End Structure
Dim pingThrd As Threading.Thread
Public Sub buttonPing_Click(sender As Object, e As EventArgs) Handles buttonPing.Click
If pingThrd Is Nothing OrElse pingThrd.ThreadState = Threading.ThreadState.Stopped Then
Dim pingTarget As String = ""
Dim numberOfPings As Integer = 0
Dim intTimeout As Integer = 2000
If String.IsNullOrEmpty(textboxIP.Text) Then
MsgBox("You must enter an IP Address or Domain.")
Exit Sub
End If
If Not Int32.TryParse(textboxPing.Text, numberOfPings) Then
MsgBox("You must enter a number of how many times the target address will be pinged.")
Exit Sub
End If
If numberOfPings = 0 Then
MsgBox("You must enter a value over 0.")
textboxPing.Clear()
Exit Sub
End If
'setup a thread to do the actual ping'ing
'this allows the UI to function
pingThrd = New Threading.Thread(AddressOf PingIt)
pingThrd.IsBackground = True
'setup address to ping and howmany times to ping it
Dim somePing As New PingWhat With {.addr = pingTarget, .howmany = numberOfPings}
'start the thread
pingThrd.Start(somePing)
End If
Me.listboxPing.Items.Add("")
End Sub
Public Sub PingIt(pingTarget As Object)
Dim pingT As PingWhat = DirectCast(pingTarget, PingWhat)
Dim pingTimeOut As Integer = 1000
Const dlyBetweenPing As Integer = 500
Dim dspStr As String
For i As Integer = 1 To pingT.howmany
Dim pingit As New Ping
Dim pingRe As PingReply = pingit.Send(pingT.addr, pingTimeOut)
'check if success
If pingRe.Status = IPStatus.Success Then
dspStr = String.Format("Response from: {0} in {1} ms.", pingRe.Address, pingRe.RoundtripTime)
Else
dspStr = String.Format("Ping Failed {0}. Status: {1}", pingT.addr, pingRe.Status)
End If
'update the UI
Me.BeginInvoke(Sub()
listboxPing.Items.Add(dspStr)
End Sub)
Threading.Thread.Sleep(dlyBetweenPing)
Next
Me.BeginInvoke(Sub()
listboxPing.Items.Add("Done")
End Sub)
End Sub
Private Sub PingClient_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
Dim Response As Integer
Response = MsgBox("Are you sure you want to exit the Ping Tool?", 36)
If Response = MsgBoxResult.Yes Then
Else
e.Cancel = True
End If
End Sub
End Class

Set string values inside for without knowing names

I am trying to find the correct way to set the string values inside the For without knowing the actual numbers. here's what i am trying to do as it was possible in vb6 but not sure using vb.net
Public Class Form1
Dim iTest1 As String
Dim iTest2 As String
Dim iTest3 As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i = 1 To 3
"iTest" & i = "aaa" & i
Next
Debug.Print("iTest1:" & iTest1)
Debug.Print("iTest2:" & iTest2)
Debug.Print("iTest3:" & iTest3)
End Sub
End Class
Try using Arrays instead.
Dim iTest(3) As String
For i = 1 To 3
iTest(i) = "aaa" & i
Next
Or this
Dim variables As New Dictionary(Of String, String)()
For i = 1 To 3
variables("iTest" + i.ToString) = "aaa" & i
Next
Console.WriteLine("iTest1:" + variables("iTest1"))
Console.WriteLine("iTest2:" + variables("iTest2"))
Console.WriteLine("iTest3:" + variables("iTest3"))
It's technically possible, but not really a recommended approach...
If you make the variables Public, then you can use the legacy CallByName() function brought over from VB6:
Public Class Form1
Public iTest1 As String
Public iTest2 As String
Public iTest3 As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 1 To 3
CallByName(Me, "iTest" & i, CallType.Let, "aaa" & i)
Next
Debug.Print("iTest1:" & iTest1)
Debug.Print("iTest2:" & iTest2)
Debug.Print("iTest3:" & iTest3)
End Sub
End Class
Without CallByName(), this can be accomplished via Reflection. Note that this works with Private or Public variables:
Public Class Form1
Private iTest1 As String
Private iTest2 As String
Private iTest3 As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim T As Type = Me.GetType
For i As Integer = 1 To 3
Dim F As Reflection.FieldInfo = T.GetField("iTest" & i, Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
If Not IsNothing(F) Then
F.SetValue(Me, "aaa" & i)
End If
Next
Debug.Print("iTest1:" & iTest1)
Debug.Print("iTest2:" & iTest2)
Debug.Print("iTest3:" & iTest3)
End Sub
End Class

Trying to make command like "Shell" with commands with RichTextBox

Trying to make command like Shell with commands with RichTextBox.
Can anyone make a simple way to make it?
im searching for this on entire webs can't find a way to make it.
So its should be like any terminal / shell / console app
So i can simply add custom commands like whatismyip its shows me my ip address etc.
Should be like this.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For I As Integer = 0 To RichTextBox1.Lines.Count - 1
Dim Parts() As String = RichTextBox1.Lines(I).Split
Select Case Parts(0).ToUpper
Case "getip"
RichTextBox1.AppendText("SYS $~ 127.0.0.1")
Case Else
RichTextBox1.AppendText("SYS $~ Invalid command.")
End Select
Next
End Sub
Try this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
commands = New Dictionary(Of String, Func(Of String, IEnumerable(Of String), String))() From _
{ _
{"getip", Function(c, ps) Me.GetIP().ToString()}, _
{"nop", Function(c, ps) "No Command"} _
}
End Sub
Private commands As Dictionary(Of String, Func(Of String, IEnumerable(Of String), String)) = Nothing
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim command = {"nop"}.Concat(Me.RichTextBox1.Lines) _
.Reverse().First(Function(l) Not [String].IsNullOrWhiteSpace(l))
If (If(Me.RichTextBox1.Lines.LastOrDefault(), "")).Length > 0 Then
Me.RichTextBox1.AppendText(Environment.NewLine)
End If
Dim parts = command.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
Dim result = "Invalid Command"
If commands.ContainsKey(parts(0).ToLower()) Then
result = commands(parts(0))(parts(0), parts.Skip(1).ToArray())
End If
Me.RichTextBox1.AppendText("SYS $~ " + result)
End Sub
Private Function GetIP() As String
Dim host As IPHostEntry
Dim localIP As String = "?"
host = Dns.GetHostEntry(Dns.GetHostName())
For Each ip As IPAddress In host.AddressList
If ip.AddressFamily = AddressFamily.InterNetwork Then
localIP = ip.ToString()
End If
Next
Return localIP
End Function
You'll need to add the following imports:
Imports System.Net
Imports System.Net.Sockets
Then you can just build out the dictionary for each of your commands.

Making a string from a listbox

I have 2 projects, one which has a highscorelist stored on it, and one which tries to add highscores to that list and retrieve all items on the list. Trying to put items on the list works good, but retrieving the list doesn't work well. Here's the code:
Option Strict On
Option Explicit On
Imports System.Net.Sockets
Imports System.Threading
Public Class Main
Dim server As New TcpListener(45888)
Dim client As New TcpClient
Dim stream As NetworkStream
Dim connected As Boolean
Private Sub cmd_start_Click(sender As Object, e As EventArgs) Handles cmd_start.Click
server.Start()
cmd_start.Enabled = False
cmd_stop.Enabled = True
lbl_status.Text = "Running"
lbl_status.ForeColor = Color.Green
tmr.Start()
End Sub
Private Sub cmd_stop_Click(sender As Object, e As EventArgs) Handles cmd_stop.Click
server.Stop()
cmd_start.Enabled = True
cmd_stop.Enabled = False
lbl_status.Text = "Not running"
lbl_status.ForeColor = Color.Red
tmr.Stop()
End Sub
Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connected = False
CheckForIllegalCrossThreadCalls = False
End Sub
Dim x As Integer = 0
Private Sub tmr_Tick(sender As Object, e As EventArgs) Handles tmr.Tick
If server.Pending Then
client = server.AcceptTcpClient()
stream = client.GetStream()
tmr.Stop()
read()
Else
tmr.Start()
End If
lbl_mseconds.Text = "Relative time: " & x
x += 1
End Sub
Private Sub SendMessage(message As String)
Dim sendtext() As Byte = System.Text.Encoding.ASCII.GetBytes(message)
stream.Write(sendtext, 0, sendtext.Length)
stream.Flush()
End Sub
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = System.Text.Encoding.ASCII.GetString(rec)
If rectext.Contains("#1#") Then
rectext = rectext.Substring(3)
If rectext.Split(CChar("-"))(0).Length = 2 Then rectext = "0" & rectext
If rectext.Split(CChar("-"))(0).Length = 1 Then rectext = "00" & rectext
listbox_highscores.Items.Add(rectext)
ElseIf rectext.Contains("#2#") Then
Dim tosend As String = listbox_highscores.Items(0).ToString
For i = 1 To listbox_highscores.Items.Count - 1
tosend &= "," & listbox_highscores.Items(i).ToString
Next
MsgBox(tosend)
SendMessage(tosend)
End If
tmr.Start()
End Sub
End Class
On the other project I have this:
Dim server As New TcpListener(45888)
Dim client As New TcpClient
Dim stream As NetworkStream
Friend Sub sendHighscore(name As String, score As Integer)
Try
client.Connect("192.168.1.127", 45888)
Catch ex As Exception
Exit Sub
End Try
stream = client.GetStream()
Dim sendtext() As Byte = Encoding.ASCII.GetBytes("#1#" & score & "-" & name)
stream.Write(sendtext, 0, sendtext.Length)
client = New TcpClient
End Sub
Friend Sub getHighscoreList()
ListBox_highscores.Items.Clear()
Try
client.Connect("192.168.1.127", 45888)
Catch ex As Exception
ListBox_highscores.Items.Add("Couldn't connect")
Exit Sub
End Try
stream = client.GetStream()
Dim sendtext() As Byte = Encoding.ASCII.GetBytes("#2#")
stream.Write(sendtext, 0, sendtext.Length)
client = New TcpClient
read()
End Sub
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = Encoding.ASCII.GetString(rec)
Label2.Text = rectext
For Each item In rectext.Split(",")
ListBox_highscores.Items.Add(item)
Next
End Sub
Then when I use the sub sendHighscore() with a name and score, everything perfectly works and it shows in the other project on the list, but when I use the sub getHighscoreList() the list on the second project only contains the first item from the first list. Does someone has ideas?
Edit: Original answer removed entirely because it wasn't actually the problem (although it did offer improvements). My answer was nearly identical to this one anyway.
After analyzing this project much more closely, the problem with the For..Next loop not returning the expected results is because the strings are being sent back and forth as byte arrays in buffers much larger than necessary (client.ReceiveBufferSize). The actual "strings" received contain large amounts of non-printable characters (garbage) added to the end to fill the buffer. The quick and dirty solution is to remove all non-printable characters:
rectext = System.Text.RegularExpressions.Regex.Replace(rectext, _
"[^\u0020-\u007F]", String.Empty)
The whole Sub would read like this:
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = System.Text.Encoding.ASCII.GetString(rec)
If rectext.Contains("#1#") Then
rectext = rectext.Substring(3)
If rectext.Split(CChar("-"))(0).Length = 2 Then rectext = "0" & rectext
If rectext.Split(CChar("-"))(0).Length = 1 Then rectext = "00" & rectext
rectext = System.Text.RegularExpressions.Regex.Replace(rectext, "[^\u0020-\u007F]", String.Empty)
listbox_highscores.Items.Add(rectext)
ElseIf rectext.Contains("#2#") Then
Dim tosend As String = listbox_highscores.Items(0).ToString
For i As Integer = 1 To (listbox_highscores.Items.Count - 1)
tosend &= "," & listbox_highscores.Items(i).ToString
Next
SendMessage(tosend)
End If
tmr.Start()
End Sub
Try this, your comma's are off as well...
Dim tosend As String = String.Empty
Dim intCount As Integer = 0
For i As Integer = 0 To listbox.Items.Count - 1
If intCount >= 1 Then
tosend &= "," & listbox.Items(i).ToString
Else
tosend &= listbox.Items(i).ToString
intCount += 1
End If
Next
MessageBox.Show(tosend)
Screenshot THAT IT WORKS!