Hallo liebes Forum!
Ich habe gestern im Rahmen eines kleines Projekts eine Funktion geschrieben die Nachrichten über das Netzwerk an eine gewünschte Ip/Port senden kann. Mir selbst ist das jetzt schon öfters untergekommen und weils mich aufregt es immer neu schreiben zu müssen (und vielleicht ein paar von euch auch) hab ich meine Lösung jetzt mal gepostet.
Viel Erfolg und Spaß!
Private Sub Test()
'Port = 1234
'IP = 127.0.0.1
SendMessageToIp("Message to send", 1234, 127, 0, 0, 1)
End Sub
''' <summary>
''' Sends a message to a given ip and port.
''' Use SendMessageToIp("Hello world!",1234, 192, 168, 2, 1)
''' </summary>
''' <param name="Message"></param>
''' <param name="Port"></param>
''' <param name="IpBlocks"></param>
''' <remarks></remarks>
Public Shared Sub SendMessageToIp(ByVal Message As String, ByVal Port As Double, ByVal ParamArray IpBlocks() As Byte)
Dim IP As System.Net.IPAddress
Select Case IpBlocks.Length
Case 1 : IP = New System.Net.IPAddress(IpBlocks(0))
Case 4, 6 : IP = New System.Net.IPAddress(IpBlocks)
Case Else : Throw New ArgumentException("Expecting parametere IpBlocks with one (ip as long), four (4 ip blocks) or six (6 ip blocks) parameter")
End Select
Dim IpEndPoint As New Net.IPEndPoint(IP, Port)
Dim SendSocket As Net.Sockets.Socket
SendSocket = New Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, _
Net.Sockets.SocketType.Stream, _
System.Net.Sockets.ProtocolType.Tcp)
SendSocket.Connect(IpEndPoint)
SendSocket.Send(System.Text.Encoding.ASCII.GetBytes(Message))
SendSocket.Close()
End Sub
Have Fun! Illias!