0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GoでTCPクライアントを秒で作る

Last updated at Posted at 2021-07-05

概要

デバッグのため、GoでのTCPリクエストのレスポンス内容を確認したかったのでさっと作った。

Docker image

$ sudo docker pull golang

main.goを作成

example.com:22の部分を接続したい宛先に変更する。

main.go
package main

import (
    "fmt"
)

import "net"

type Client struct {
    addr string
}

func NewClient(addr string) *Client {
    return &Client{addr: addr}
}

func (c *Client) Request() (string, error) {
    conn, err := net.Dial("tcp", c.addr)
    if err != nil {
        return "", err
    }
    defer conn.Close()

    buf := make([]byte, 1024)
    n, err := conn.Read(buf)
    if err != nil {
        return "", err
    }

    return string(buf[:n]), nil
}

func main() {
    // 接続先。22番ポートにアクセスする例。
    dst := "example.com:22"
    c := NewClient(dst)

    // 
    resp, err := c.Request()
    if err != nil {
        panic(err)
    }

    fmt.Println(resp)
}

Dockerコンテナを起動してmain.goをcp

# コンテナ起動
$ docker run -d --rm --name go-tcp-client -w /go/src -it golang /bin/bash
# go module作成
$ docker exec -w /go/src -it go-tcp-client /bin/bash -c 'go mod init tcp-client'
# main.goをコンテナへcp
$ docker cp main.go go-tcp-client:/go/src/

実行

$ docker exec -w /go/src -it go-tcp-client /bin/bash -c 'go run .'
SSH-2.0-OpenSSH_7.4

関連記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?