A
A
Alexander Ampleev2019-08-10 20:27:24
go
Alexander Ampleev, 2019-08-10 20:27:24

Why doesn't a remote client connect to a simple golang server running locally?

Here is a simple server on th

package main

import (
  "bufio"
  "fmt"
  "log"
  "net"
)

// Our server
const (
  HOST = ""
  PORT = "8080"
  TYPE = "tcp4"
)

func main() {

  listener, err := net.Listen(TYPE, fmt.Sprintf("%s:%s", HOST, PORT))
  if err != nil {
    log.Fatal("Error listening " + err.Error())
  }

  defer func() {
    if err := listener.Close(); err != nil {
      fmt.Println("Error stoping listener")
      fmt.Println("Listener closed.")
    }
  }()

  fmt.Printf("[+] Server listening on %s:%s type %s\n", HOST, PORT, TYPE)

  for {

    connection, err := listener.Accept()
    if err != nil {
      fmt.Println("Error accepting connection ", err.Error())
      continue
    }

    fmt.Println("Accepted connection: ", connection.RemoteAddr().String())

    go handleRequest(connection)

  }

}

func handleRequest(connection net.Conn) error {

  defer func() {
    if err := connection.Close(); err != nil {
      fmt.Println("Error closing connection: ", err.Error())
    }
  }()

  r := bufio.NewReader(connection)
  w := bufio.NewWriter(connection)
  scanr := bufio.NewScanner(r)

  for {
    scanned := scanr.Scan()

    if !scanned {
      if err := scanr.Err(); err != nil {
        log.Printf("Scanning error on %v(%v)", err, connection.RemoteAddr().String())
        return err
      }
    }

    text := scanr.Text()
    fmt.Printf("Recieved data from %s: %s\n", connection.RemoteAddr().String(), text)
    w.WriteString(text + "\r\n")
    w.Flush()

    if text == "quit" || text == "exit" {
      fmt.Println("Recieved exit request", connection.RemoteAddr().String(), text)
      break
    }
  }

  return nil

}

I look locally at my ip address: 192.168.31.245 I start the
virtual machine and in it through telnet 192.168.31.245 8080 I get this command to connect, everything is ok.
In the same way, I try to connect to a remote server dedicated to centos and constantly writes "Trying 192.168.31.243 ..." but the connection itself does not go ..
What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
falconandy, 2019-08-10
@falconandy

192.168.31.245 is a local IP address, but you need an external IP address.
You can use ngrok

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question