Answer the question
In order to leave comments, you need to log in
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
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question