Savan
Savan

Reputation: 11

Socket Client and Server Not Working

**Server Code**

Dim serverSocket As Socket
Dim clientSocket As Socket
Dim PubIP as String = "82.XX.XX.XX"
Dim LocalIP as String = "192.XX.XX.XX"

Dim byteData(1023) As Byte

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim host As String = Dns.GetHostName
    Dim ip As IPHostEntry = Dns.GetHostEntry(host)
    serverSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    Dim IpEndPoint As IPEndPoint = New IPEndPoint(System.Net.IPAddress.Parse(PubIP), 8080) 
    Me.Text = IpEndPoint.ToString
    serverSocket.Bind(IpEndPoint) 'it can't bind public ip but i need public ip to run the client from other pc and connect to server for chating.
    serverSocket.Listen(5)
    serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
End Sub

**Client Code**

Dim clientSocket As Socket
Dim byteData(1023) As Byte

Dim PubIP as String = "82.XX.XX.XX"
Dim LocalIP as String = "192.XX.XX.XX"

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    clientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    Dim ipAddress As IPAddress = ipAddress.Parse(PubIP)
    Dim ipEndPoint As IPEndPoint = New IPEndPoint(ipAddress, 8080)
    clientSocket.BeginConnect(ipEndPoint, New AsyncCallback(AddressOf OnConnect), Nothing)
End Sub

when i run the server with localip, it runs fine and i am only able to connect client from my computer only (where server runs). if i try to run the client from another computer, it won't connect to server.

so i assigned public ip but when i run the program visual studio shows this error:The requested address is not valid in its context.

so i am stuck here. i am only able to connect client if run from my computer but i need to connect the client from my friend pc to my server in my pc.

any alternative ways are welcome.

Upvotes: 1

Views: 918

Answers (1)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84151

Use IPAddress.Any instead of a specific IP address to make your server accept connections on all interfaces.

Other then that, since you mention "local" and "public" IP addresses, you need to understand Network Address Translation and port forwarding.

Upvotes: 1

Related Questions