콘텐츠로 이동
Search

Go:net

lastmod 2026-11-10created 2025-11-282 edits

net 패키지는 Go 표준 라이브러리에서 TCP/IP, UDP, 유닉스 도메인 소켓, 도메인 이름 해석 등 네트워크 입출력을 담당한다. Dial() 로 연결을 만들고 Listen() 으로 수신 대기하며 그 결과를 Conn, Listener 인터페이스로 다루고, IP, IPNet, TCPAddr 같은 주소 타입과 SplitHostPort(), JoinHostPort(), ParseIP(), LookupHost() 같은 도우미 함수를 제공한다. net/http 등 상위 패키지들이 이 위에 구현되어 있다.

SplitHostPort

// SplitHostPort splits a network address of the form "host:port",
// "host%zone:port", "[host]:port" or "[host%zone]:port" into host or
// host%zone and port.
//
// A literal IPv6 address in hostport must be enclosed in square
// brackets, as in "[::1]:80", "[::1%lo0]:80".
//
// See func Dial for a description of the hostport parameter, and host
// and port results.
func SplitHostPort(hostport string) (host, port string, err error) {
    const (
        missingPort   = "missing port in address"
        tooManyColons = "too many colons in address"
    )
    addrErr := func(addr, why string) (host, port string, err error) {
        return "", "", &AddrError{Err: why, Addr: addr}
    }
    j, k := 0, 0

    // The port starts after the last colon.
    i := bytealg.LastIndexByteString(hostport, ':')
    if i < 0 {
        return addrErr(hostport, missingPort)
    }

    if hostport[0] == '[' {
        // Expect the first ']' just before the last ':'.
        end := bytealg.IndexByteString(hostport, ']')
        if end < 0 {
            return addrErr(hostport, "missing ']' in address")
        }
        switch end + 1 {
        case len(hostport):
            // There can't be a ':' behind the ']' now.
            return addrErr(hostport, missingPort)
        case i:
            // The expected result.
        default:
            // Either ']' isn't followed by a colon, or it is
            // followed by a colon that is not the last one.
            if hostport[end+1] == ':' {
                return addrErr(hostport, tooManyColons)
            }
            return addrErr(hostport, missingPort)
        }
        host = hostport[1:end]
        j, k = 1, end+1 // there can't be a '[' resp. ']' before these positions
    } else {
        host = hostport[:i]
        if bytealg.IndexByteString(host, ':') >= 0 {
            return addrErr(hostport, tooManyColons)
        }
    }
    if bytealg.IndexByteString(hostport[j:], '[') >= 0 {
        return addrErr(hostport, "unexpected '[' in address")
    }
    if bytealg.IndexByteString(hostport[k:], ']') >= 0 {
        return addrErr(hostport, "unexpected ']' in address")
    }

    port = hostport[i+1:]
    return host, port, nil
}

See also

author Zer0, MCPBot sitemap