【发布时间】:2013-10-26 08:19:44
【问题描述】:
我正在发送带有消息“你好?”的 UDP 广播。使用此代码:
Public Sub UDPSendHello()
Dim client As New UDPClient()
Dim ip As New IPEndPoint(IPAddress.Broadcast, 15000)
Dim bytes As Byte() = Encoding.ASCII.GetBytes("Hello?")
client.Send(bytes, bytes.Length, ip)
client.Close()
End Sub
当然,UDPListner 可以正常接收消息!
Private ReadOnly udp As New UdpClient(15000)
Public Sub UDPHelloListner()
udp.BeginReceive(AddressOf Receive, New Object())
End Sub
Private Sub Receive(ByVal ar As IAsyncResult)
Dim ip As New IPEndPoint(IPAddress.Any, 15000)
Dim bytes As Byte() = udp.EndReceive(ar, ip)
Dim message As String = Encoding.ASCII.GetString(bytes)
If message = "Hello?" Then
Dim sender As New IPEndPoint(IPAddress.Any, 15000)
Dim senderRemote As EndPoint = CType(sender, EndPoint)
MessageBox.Show("I see message, Hello")
End If
UDPHelloListner()
End Sub
那么我怎样才能获得发件人的 IP 地址并将其显示在消息框、文本框等中。
我看到了Socket.RecieveFrom 方法,但是!在以下代码的这一点上,我收到此错误"The system detected an invalid pointer address in attempting to use a pointer argument in a call",“s.ReceiveFrom(msg, SocketFlags.None, senderRemote)”
Public Sub ReceiveFrom2()
Dim hostEntry As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
Dim endPoint As New IPEndPoint(hostEntry.AddressList(0), 11000)
Dim s As New Socket(EndPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
' Creates an IpEndPoint to capture the identity of the sending host.
Dim sender As New IPEndPoint(IPAddress.Any, 0)
Dim senderRemote As EndPoint = CType(sender, EndPoint)
' Binding is required with ReceiveFrom calls.
s.Bind(endPoint)
Dim msg() As Byte = New [Byte](255) {}
Console.WriteLine("Waiting to receive datagrams from client...")
' This call blocks.
s.ReceiveFrom(msg, SocketFlags.None, senderRemote)
s.Close()
End Sub 'ReceiveFrom2
那么我将如何获取发件人 IP 并使用上面的代码在文本框、消息等中显示它......????
【问题讨论】: