proxyprotocol.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Copyright 2025 The frp Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package net
  15. import (
  16. "bytes"
  17. "fmt"
  18. "net"
  19. pp "github.com/pires/go-proxyproto"
  20. )
  21. func BuildProxyProtocolHeaderStruct(srcAddr, dstAddr net.Addr, version string) *pp.Header {
  22. var versionByte byte
  23. if version == "v1" {
  24. versionByte = 1
  25. } else {
  26. versionByte = 2 // default to v2
  27. }
  28. return pp.HeaderProxyFromAddrs(versionByte, srcAddr, dstAddr)
  29. }
  30. func BuildProxyProtocolHeader(srcAddr, dstAddr net.Addr, version string) ([]byte, error) {
  31. h := BuildProxyProtocolHeaderStruct(srcAddr, dstAddr, version)
  32. // Convert header to bytes using a buffer
  33. var buf bytes.Buffer
  34. _, err := h.WriteTo(&buf)
  35. if err != nil {
  36. return nil, fmt.Errorf("failed to write proxy protocol header: %v", err)
  37. }
  38. return buf.Bytes(), nil
  39. }