menu

arrow_back Why not connect a remote client to a simple server running locally on golang?

by
2 votes
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

}


Смотрю локально свой ip адрес: 192.168.31.245

Запускаю виртуалку и в ней через telnet 192.168.31.245 8080 эту команду получаю соединение, все ок.

Таким же образом пытаюсь подключиться на удаленном сервере выделенном на центосе и постоянно пишет "Trying 192.168.31.243..." но само подключение не идет..

В чем может быть проблема?

1 comment

But on a remote dedicated which IP address?

1 Answer

by
2 votes
192.168.31.245 is a local IP address and the desired IP address.
You can use ngrok