2020-10-09

package main

import (
	"net"
	"os"
	"io"
	"bytes"
	"fmt"
)

func checkSum(msg []byte) uint16 {
     
	sum := 0
	n := 0
	for n+1 < len(msg) {
     
		sum += (int(msg[n]) << 8)
	}
	sum = (sum >> 16) + (sum & 0xffff)
	sum += (sum >> 16)
	return uint16(^sum)
}

func checkError(err error) {
     
	if err != nil {
     
		fmt.Fprintf(os.Stderr, "Fatal error : %s", err.Error())
		os.Exit(1)
	}
}

func readFully(conn net.Conn) ([]byte, error) {
     
	defer conn.Close()

	result := bytes.NewBuffer(nil)
	var buf [512]byte
	for {
     
		n, err := conn.Read(buf[0:])
		result.Write(buf[0:n])
		if err != nil {
     
			if err == io.EOF {
     
				break
			}
			return nil, err
		}
	}
	return result.Bytes(), nil
}

/*
os.Args[0] 接收第一个参数是文件路径
os.Args[1] 接收第二个参数是输入的参数
*/



func main() {
     
	if len(os.Args) != 2 {
     
		fmt.Fprintf(os.Stderr, "Usage: %s host:port", os.Args[0])
		os.Exit(1)
	}
	service := os.Args[1]

	conn, err := net.Dial("tcp", service)
	checkError(err)

	_, err = conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))
	checkError(err)

	result, err := readFully(conn)
	checkError(err)

	fmt.Println(string(result))

	os.Exit(0)
}















你可能感兴趣的:(go)