Skip to content

Instantly share code, notes, and snippets.

@goldeneggg
Last active September 6, 2023 04:41
Show Gist options
  • Save goldeneggg/996e1ad0fbd29d8fe7576df215b9927f to your computer and use it in GitHub Desktop.
Save goldeneggg/996e1ad0fbd29d8fe7576df215b9927f to your computer and use it in GitHub Desktop.
TELNET or TELNETS(TELNET over SSL) to koukoku.shadan.open.ad.jp in Go
package main
import (
"bufio"
"bytes"
"crypto/tls"
"fmt"
"io"
"log"
"net"
"os"
"golang.org/x/text/encoding/japanese"
"golang.org/x/text/transform"
)
const (
host = "koukoku.shadan.open.ad.jp"
)
var (
addrTelnet = fmt.Sprintf("%s:23", host)
addrTelnetS = fmt.Sprintf("%s:992", host)
)
// If you want to connect with TELNET, run `go run main.go t`.
// If you want to connect with TELNETS, run `go run main.go s`.
// This program should be run on a terminal with the character encoding set to UTF-8.
func main() {
var conn net.Conn
var isNotUTF8 bool
var err error
if len(os.Args) != 2 {
log.Fatalf("expected argument length is 2 but actual is %d", len(os.Args))
}
switch os.Args[1] {
case "t":
// TELNET
conn, err = net.Dial("tcp", addrTelnet)
isNotUTF8 = true
case "s":
// TELNETS
conn, err = tls.Dial("tcp", addrTelnetS, &tls.Config{})
default:
log.Fatalf("invalid argument %q\n", os.Args[1])
}
if err != nil {
log.Fatalf("failed to connect to %q with %q mode. err: %v\n", host, os.Args[1], err)
}
defer conn.Close()
telnet(conn, isNotUTF8)
}
func telnet(conn net.Conn, isNotUTF8 bool) {
reader := bufio.NewReader(conn)
for {
line, err := reader.ReadString('\n')
if err != nil {
break
}
if isNotUTF8 {
line, err = toUTF8(line)
if err != nil {
log.Fatalf("failed to decode to utf8. err: %v\n", err)
}
}
fmt.Print(line)
}
}
func toUTF8(org string) (string, error) {
decoded, err := io.ReadAll(transform.NewReader(bytes.NewReader([]byte(org)), japanese.ShiftJIS.NewDecoder()))
if err != nil {
return "", err
}
return string(decoded), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment