2
0

srt.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. // Copyright (c) 2024 Winlin
  2. //
  3. // SPDX-License-Identifier: MIT
  4. package main
  5. import (
  6. "bytes"
  7. "context"
  8. "encoding/binary"
  9. "fmt"
  10. "net"
  11. "strings"
  12. stdSync "sync"
  13. "time"
  14. "srs-proxy/errors"
  15. "srs-proxy/logger"
  16. "srs-proxy/sync"
  17. )
  18. // srsSRTServer is the proxy for SRS server via SRT. It will figure out which backend server to
  19. // proxy to. It only parses the SRT handshake messages, parses the stream id, and proxy to the
  20. // backend server.
  21. type srsSRTServer struct {
  22. // The UDP listener for SRT server.
  23. listener *net.UDPConn
  24. // The SRT connections, identify by the socket ID.
  25. sockets sync.Map[uint32, *SRTConnection]
  26. // The system start time.
  27. start time.Time
  28. // The wait group for server.
  29. wg stdSync.WaitGroup
  30. }
  31. func NewSRSSRTServer(opts ...func(*srsSRTServer)) *srsSRTServer {
  32. v := &srsSRTServer{
  33. start: time.Now(),
  34. }
  35. for _, opt := range opts {
  36. opt(v)
  37. }
  38. return v
  39. }
  40. func (v *srsSRTServer) Close() error {
  41. if v.listener != nil {
  42. v.listener.Close()
  43. }
  44. v.wg.Wait()
  45. return nil
  46. }
  47. func (v *srsSRTServer) Run(ctx context.Context) error {
  48. // Parse address to listen.
  49. endpoint := envSRTServer()
  50. if !strings.Contains(endpoint, ":") {
  51. endpoint = ":" + endpoint
  52. }
  53. saddr, err := net.ResolveUDPAddr("udp", endpoint)
  54. if err != nil {
  55. return errors.Wrapf(err, "resolve udp addr %v", endpoint)
  56. }
  57. listener, err := net.ListenUDP("udp", saddr)
  58. if err != nil {
  59. return errors.Wrapf(err, "listen udp %v", saddr)
  60. }
  61. v.listener = listener
  62. logger.Df(ctx, "SRT server listen at %v", saddr)
  63. // Consume all messages from UDP media transport.
  64. v.wg.Add(1)
  65. go func() {
  66. defer v.wg.Done()
  67. for ctx.Err() == nil {
  68. buf := make([]byte, 4096)
  69. n, caddr, err := v.listener.ReadFromUDP(buf)
  70. if err != nil {
  71. // TODO: If SRT server closed unexpectedly, we should notice the main loop to quit.
  72. logger.Wf(ctx, "read from udp failed, err=%+v", err)
  73. continue
  74. }
  75. if err := v.handleClientUDP(ctx, caddr, buf[:n]); err != nil {
  76. logger.Wf(ctx, "handle udp %vB failed, addr=%v, err=%+v", n, caddr, err)
  77. }
  78. }
  79. }()
  80. return nil
  81. }
  82. func (v *srsSRTServer) handleClientUDP(ctx context.Context, addr *net.UDPAddr, data []byte) error {
  83. socketID := srtParseSocketID(data)
  84. var pkt *SRTHandshakePacket
  85. if srtIsHandshake(data) {
  86. pkt = &SRTHandshakePacket{}
  87. if err := pkt.UnmarshalBinary(data); err != nil {
  88. return err
  89. }
  90. if socketID == 0 {
  91. socketID = pkt.SRTSocketID
  92. }
  93. }
  94. conn, ok := v.sockets.LoadOrStore(socketID, NewSRTConnection(func(c *SRTConnection) {
  95. c.ctx = logger.WithContext(ctx)
  96. c.listenerUDP, c.socketID = v.listener, socketID
  97. c.start = v.start
  98. }))
  99. ctx = conn.ctx
  100. if !ok {
  101. logger.Df(ctx, "Create new SRT connection skt=%v", socketID)
  102. }
  103. if newSocketID, err := conn.HandlePacket(pkt, addr, data); err != nil {
  104. return errors.Wrapf(err, "handle packet")
  105. } else if newSocketID != 0 && newSocketID != socketID {
  106. // The connection may use a new socket ID.
  107. // TODO: FIXME: Should cleanup the dead SRT connection.
  108. v.sockets.Store(newSocketID, conn)
  109. }
  110. return nil
  111. }
  112. // SRTConnection is an SRT connection proxy, for both caller and listener. It represents an SRT
  113. // connection, identify by the socket ID.
  114. //
  115. // It's similar to RTMP or HTTP FLV/TS proxy connection, which are stateless and all state is in
  116. // the client request. The SRTConnection is stateless, and no need to sync between proxy servers.
  117. //
  118. // Unlike the WebRTC connection, SRTConnection does not support address changes. This means the
  119. // client should never switch to another network or port. If this occurs, the client may be served
  120. // by a different proxy server and fail because the other proxy server cannot identify the client.
  121. type SRTConnection struct {
  122. // The stream context for SRT connection.
  123. ctx context.Context
  124. // The current socket ID.
  125. socketID uint32
  126. // The UDP connection proxy to backend.
  127. backendUDP *net.UDPConn
  128. // The listener UDP connection, used to send messages to client.
  129. listenerUDP *net.UDPConn
  130. // Listener start time.
  131. start time.Time
  132. // Handshake packets with client.
  133. handshake0 *SRTHandshakePacket
  134. handshake1 *SRTHandshakePacket
  135. handshake2 *SRTHandshakePacket
  136. handshake3 *SRTHandshakePacket
  137. }
  138. func NewSRTConnection(opts ...func(*SRTConnection)) *SRTConnection {
  139. v := &SRTConnection{}
  140. for _, opt := range opts {
  141. opt(v)
  142. }
  143. return v
  144. }
  145. func (v *SRTConnection) HandlePacket(pkt *SRTHandshakePacket, addr *net.UDPAddr, data []byte) (uint32, error) {
  146. ctx := v.ctx
  147. // If not handshake, try to proxy to backend directly.
  148. if pkt == nil {
  149. // Proxy client message to backend.
  150. if v.backendUDP != nil {
  151. if _, err := v.backendUDP.Write(data); err != nil {
  152. return v.socketID, errors.Wrapf(err, "write to backend")
  153. }
  154. }
  155. return v.socketID, nil
  156. }
  157. // Handle handshake messages.
  158. if err := v.handleHandshake(ctx, pkt, addr, data); err != nil {
  159. return v.socketID, errors.Wrapf(err, "handle handshake %v", pkt)
  160. }
  161. return v.socketID, nil
  162. }
  163. func (v *SRTConnection) handleHandshake(ctx context.Context, pkt *SRTHandshakePacket, addr *net.UDPAddr, data []byte) error {
  164. // Handle handshake 0 and 1 messages.
  165. if pkt.SynCookie == 0 {
  166. // Save handshake 0 packet.
  167. v.handshake0 = pkt
  168. logger.Df(ctx, "SRT Handshake 0: %v", v.handshake0)
  169. // Response handshake 1.
  170. v.handshake1 = &SRTHandshakePacket{
  171. ControlFlag: pkt.ControlFlag,
  172. ControlType: 0,
  173. SubType: 0,
  174. AdditionalInfo: 0,
  175. Timestamp: uint32(time.Since(v.start).Microseconds()),
  176. SocketID: pkt.SRTSocketID,
  177. Version: 5,
  178. EncryptionField: 0,
  179. ExtensionField: 0x4A17,
  180. InitSequence: pkt.InitSequence,
  181. MTU: pkt.MTU,
  182. FlowWindow: pkt.FlowWindow,
  183. HandshakeType: 1,
  184. SRTSocketID: pkt.SRTSocketID,
  185. SynCookie: 0x418d5e4e,
  186. PeerIP: net.ParseIP("127.0.0.1"),
  187. }
  188. logger.Df(ctx, "SRT Handshake 1: %v", v.handshake1)
  189. if b, err := v.handshake1.MarshalBinary(); err != nil {
  190. return errors.Wrapf(err, "marshal handshake 1")
  191. } else if _, err = v.listenerUDP.WriteToUDP(b, addr); err != nil {
  192. return errors.Wrapf(err, "write handshake 1")
  193. }
  194. return nil
  195. }
  196. // Handle handshake 2 and 3 messages.
  197. // Parse stream id from packet.
  198. streamID, err := pkt.StreamID()
  199. if err != nil {
  200. return errors.Wrapf(err, "parse stream id")
  201. }
  202. // Save handshake packet.
  203. v.handshake2 = pkt
  204. logger.Df(ctx, "SRT Handshake 2: %v, sid=%v", v.handshake2, streamID)
  205. // Start the UDP proxy to backend.
  206. if err := v.connectBackend(ctx, streamID); err != nil {
  207. return errors.Wrapf(err, "connect backend for %v", streamID)
  208. }
  209. // Proxy client message to backend.
  210. if v.backendUDP == nil {
  211. return errors.Errorf("no backend for %v", streamID)
  212. }
  213. // Proxy handshake 0 to backend server.
  214. if b, err := v.handshake0.MarshalBinary(); err != nil {
  215. return errors.Wrapf(err, "marshal handshake 0")
  216. } else if _, err = v.backendUDP.Write(b); err != nil {
  217. return errors.Wrapf(err, "write handshake 0")
  218. }
  219. logger.Df(ctx, "Proxy send handshake 0: %v", v.handshake0)
  220. // Read handshake 1 from backend server.
  221. b := make([]byte, 4096)
  222. handshake1p := &SRTHandshakePacket{}
  223. if nn, err := v.backendUDP.Read(b); err != nil {
  224. return errors.Wrapf(err, "read handshake 1")
  225. } else if err := handshake1p.UnmarshalBinary(b[:nn]); err != nil {
  226. return errors.Wrapf(err, "unmarshal handshake 1")
  227. }
  228. logger.Df(ctx, "Proxy got handshake 1: %v", handshake1p)
  229. // Proxy handshake 2 to backend server.
  230. handshake2p := *v.handshake2
  231. handshake2p.SynCookie = handshake1p.SynCookie
  232. if b, err := handshake2p.MarshalBinary(); err != nil {
  233. return errors.Wrapf(err, "marshal handshake 2")
  234. } else if _, err = v.backendUDP.Write(b); err != nil {
  235. return errors.Wrapf(err, "write handshake 2")
  236. }
  237. logger.Df(ctx, "Proxy send handshake 2: %v", handshake2p)
  238. // Read handshake 3 from backend server.
  239. handshake3p := &SRTHandshakePacket{}
  240. if nn, err := v.backendUDP.Read(b); err != nil {
  241. return errors.Wrapf(err, "read handshake 3")
  242. } else if err := handshake3p.UnmarshalBinary(b[:nn]); err != nil {
  243. return errors.Wrapf(err, "unmarshal handshake 3")
  244. }
  245. logger.Df(ctx, "Proxy got handshake 3: %v", handshake3p)
  246. // Response handshake 3 to client.
  247. v.handshake3 = &*handshake3p
  248. v.handshake3.SynCookie = v.handshake1.SynCookie
  249. v.socketID = handshake3p.SRTSocketID
  250. logger.Df(ctx, "Handshake 3: %v", v.handshake3)
  251. if b, err := v.handshake3.MarshalBinary(); err != nil {
  252. return errors.Wrapf(err, "marshal handshake 3")
  253. } else if _, err = v.listenerUDP.WriteToUDP(b, addr); err != nil {
  254. return errors.Wrapf(err, "write handshake 3")
  255. }
  256. // Start a goroutine to proxy message from backend to client.
  257. // TODO: FIXME: Support close the connection when timeout or client disconnected.
  258. go func() {
  259. for ctx.Err() == nil {
  260. nn, err := v.backendUDP.Read(b)
  261. if err != nil {
  262. // TODO: If backend server closed unexpectedly, we should notice the stream to quit.
  263. logger.Wf(ctx, "read from backend failed, err=%v", err)
  264. return
  265. }
  266. if _, err = v.listenerUDP.WriteToUDP(b[:nn], addr); err != nil {
  267. // TODO: If backend server closed unexpectedly, we should notice the stream to quit.
  268. logger.Wf(ctx, "write to client failed, err=%v", err)
  269. return
  270. }
  271. }
  272. }()
  273. return nil
  274. }
  275. func (v *SRTConnection) connectBackend(ctx context.Context, streamID string) error {
  276. if v.backendUDP != nil {
  277. return nil
  278. }
  279. // Parse stream id to host and resource.
  280. host, resource, err := parseSRTStreamID(streamID)
  281. if err != nil {
  282. return errors.Wrapf(err, "parse stream id %v", streamID)
  283. }
  284. if host == "" {
  285. host = "localhost"
  286. }
  287. streamURL, err := buildStreamURL(fmt.Sprintf("srt://%v/%v", host, resource))
  288. if err != nil {
  289. return errors.Wrapf(err, "build stream url %v", streamID)
  290. }
  291. // Pick a backend SRS server to proxy the SRT stream.
  292. backend, err := srsLoadBalancer.Pick(ctx, streamURL)
  293. if err != nil {
  294. return errors.Wrapf(err, "pick backend for %v", streamURL)
  295. }
  296. // Parse UDP port from backend.
  297. if len(backend.SRT) == 0 {
  298. return errors.Errorf("no udp server %v for %v", backend, streamURL)
  299. }
  300. _, _, udpPort, err := parseListenEndpoint(backend.SRT[0])
  301. if err != nil {
  302. return errors.Wrapf(err, "parse udp port %v of %v for %v", backend.SRT[0], backend, streamURL)
  303. }
  304. // Connect to backend SRS server via UDP client.
  305. // TODO: FIXME: Support close the connection when timeout or client disconnected.
  306. backendAddr := net.UDPAddr{IP: net.ParseIP(backend.IP), Port: int(udpPort)}
  307. if backendUDP, err := net.DialUDP("udp", nil, &backendAddr); err != nil {
  308. return errors.Wrapf(err, "dial udp to %v of %v for %v", backendAddr, backend, streamURL)
  309. } else {
  310. v.backendUDP = backendUDP
  311. }
  312. return nil
  313. }
  314. // See https://datatracker.ietf.org/doc/html/draft-sharabayko-srt-01#section-3.2
  315. // See https://datatracker.ietf.org/doc/html/draft-sharabayko-srt-01#section-3.2.1
  316. type SRTHandshakePacket struct {
  317. // F: 1 bit. Packet Type Flag. The control packet has this flag set to
  318. // "1". The data packet has this flag set to "0".
  319. ControlFlag uint8
  320. // Control Type: 15 bits. Control Packet Type. The use of these bits
  321. // is determined by the control packet type definition.
  322. // Handshake control packets (Control Type = 0x0000) are used to
  323. // exchange peer configurations, to agree on connection parameters, and
  324. // to establish a connection.
  325. ControlType uint16
  326. // Subtype: 16 bits. This field specifies an additional subtype for
  327. // specific packets.
  328. SubType uint16
  329. // Type-specific Information: 32 bits. The use of this field depends on
  330. // the particular control packet type. Handshake packets do not use
  331. // this field.
  332. AdditionalInfo uint32
  333. // Timestamp: 32 bits.
  334. Timestamp uint32
  335. // Destination Socket ID: 32 bits.
  336. SocketID uint32
  337. // Version: 32 bits. A base protocol version number. Currently used
  338. // values are 4 and 5. Values greater than 5 are reserved for future
  339. // use.
  340. Version uint32
  341. // Encryption Field: 16 bits. Block cipher family and key size. The
  342. // values of this field are described in Table 2. The default value
  343. // is AES-128.
  344. // 0 | No Encryption Advertised
  345. // 2 | AES-128
  346. // 3 | AES-192
  347. // 4 | AES-256
  348. EncryptionField uint16
  349. // Extension Field: 16 bits. This field is message specific extension
  350. // related to Handshake Type field. The value MUST be set to 0
  351. // except for the following cases. (1) If the handshake control
  352. // packet is the INDUCTION message, this field is sent back by the
  353. // Listener. (2) In the case of a CONCLUSION message, this field
  354. // value should contain a combination of Extension Type values.
  355. // 0x00000001 | HSREQ
  356. // 0x00000002 | KMREQ
  357. // 0x00000004 | CONFIG
  358. // 0x4A17 if HandshakeType is INDUCTION, see https://datatracker.ietf.org/doc/html/draft-sharabayko-srt-01#section-4.3.1.1
  359. ExtensionField uint16
  360. // Initial Packet Sequence Number: 32 bits. The sequence number of the
  361. // very first data packet to be sent.
  362. InitSequence uint32
  363. // Maximum Transmission Unit Size: 32 bits. This value is typically set
  364. // to 1500, which is the default Maximum Transmission Unit (MTU) size
  365. // for Ethernet, but can be less.
  366. MTU uint32
  367. // Maximum Flow Window Size: 32 bits. The value of this field is the
  368. // maximum number of data packets allowed to be "in flight" (i.e. the
  369. // number of sent packets for which an ACK control packet has not yet
  370. // been received).
  371. FlowWindow uint32
  372. // Handshake Type: 32 bits. This field indicates the handshake packet
  373. // type.
  374. // 0xFFFFFFFD | DONE
  375. // 0xFFFFFFFE | AGREEMENT
  376. // 0xFFFFFFFF | CONCLUSION
  377. // 0x00000000 | WAVEHAND
  378. // 0x00000001 | INDUCTION
  379. HandshakeType uint32
  380. // SRT Socket ID: 32 bits. This field holds the ID of the source SRT
  381. // socket from which a handshake packet is issued.
  382. SRTSocketID uint32
  383. // SYN Cookie: 32 bits. Randomized value for processing a handshake.
  384. // The value of this field is specified by the handshake message
  385. // type.
  386. SynCookie uint32
  387. // Peer IP Address: 128 bits. IPv4 or IPv6 address of the packet's
  388. // sender. The value consists of four 32-bit fields.
  389. PeerIP net.IP
  390. // Extensions.
  391. // Extension Type: 16 bits. The value of this field is used to process
  392. // an integrated handshake. Each extension can have a pair of
  393. // request and response types.
  394. // Extension Length: 16 bits. The length of the Extension Contents
  395. // field in four-byte blocks.
  396. // Extension Contents: variable length. The payload of the extension.
  397. ExtraData []byte
  398. }
  399. func (v *SRTHandshakePacket) IsData() bool {
  400. return v.ControlFlag == 0x00
  401. }
  402. func (v *SRTHandshakePacket) IsControl() bool {
  403. return v.ControlFlag == 0x80
  404. }
  405. func (v *SRTHandshakePacket) IsHandshake() bool {
  406. return v.IsControl() && v.ControlType == 0x00 && v.SubType == 0x00
  407. }
  408. func (v *SRTHandshakePacket) StreamID() (string, error) {
  409. p := v.ExtraData
  410. for {
  411. if len(p) < 2 {
  412. return "", errors.Errorf("Require 2 bytes, actual=%v, extra=%v", len(p), len(v.ExtraData))
  413. }
  414. extType := binary.BigEndian.Uint16(p)
  415. extSize := binary.BigEndian.Uint16(p[2:])
  416. p = p[4:]
  417. if len(p) < int(extSize*4) {
  418. return "", errors.Errorf("Require %v bytes, actual=%v, extra=%v", extSize*4, len(p), len(v.ExtraData))
  419. }
  420. // Ignore other packets except stream id.
  421. if extType != 0x05 {
  422. p = p[extSize*4:]
  423. continue
  424. }
  425. // We must copy it, because we will decode the stream id.
  426. data := append([]byte{}, p[:extSize*4]...)
  427. // Reverse the stream id encoded in little-endian to big-endian.
  428. for i := 0; i < len(data); i += 4 {
  429. value := binary.LittleEndian.Uint32(data[i:])
  430. binary.BigEndian.PutUint32(data[i:], value)
  431. }
  432. // Trim the trailing zero bytes.
  433. data = bytes.TrimRight(data, "\x00")
  434. return string(data), nil
  435. }
  436. }
  437. func (v *SRTHandshakePacket) String() string {
  438. return fmt.Sprintf("Control=%v, CType=%v, SType=%v, Timestamp=%v, SocketID=%v, Version=%v, Encrypt=%v, Extension=%v, InitSequence=%v, MTU=%v, FlowWnd=%v, HSType=%v, SRTSocketID=%v, Cookie=%v, Peer=%vB, Extra=%vB",
  439. v.IsControl(), v.ControlType, v.SubType, v.Timestamp, v.SocketID, v.Version, v.EncryptionField, v.ExtensionField, v.InitSequence, v.MTU, v.FlowWindow, v.HandshakeType, v.SRTSocketID, v.SynCookie, len(v.PeerIP), len(v.ExtraData))
  440. }
  441. func (v *SRTHandshakePacket) UnmarshalBinary(b []byte) error {
  442. if len(b) < 4 {
  443. return errors.Errorf("Invalid packet length %v", len(b))
  444. }
  445. v.ControlFlag = b[0] & 0x80
  446. v.ControlType = binary.BigEndian.Uint16(b[0:2]) & 0x7fff
  447. v.SubType = binary.BigEndian.Uint16(b[2:4])
  448. if len(b) < 64 {
  449. return errors.Errorf("Invalid packet length %v", len(b))
  450. }
  451. v.AdditionalInfo = binary.BigEndian.Uint32(b[4:])
  452. v.Timestamp = binary.BigEndian.Uint32(b[8:])
  453. v.SocketID = binary.BigEndian.Uint32(b[12:])
  454. v.Version = binary.BigEndian.Uint32(b[16:])
  455. v.EncryptionField = binary.BigEndian.Uint16(b[20:])
  456. v.ExtensionField = binary.BigEndian.Uint16(b[22:])
  457. v.InitSequence = binary.BigEndian.Uint32(b[24:])
  458. v.MTU = binary.BigEndian.Uint32(b[28:])
  459. v.FlowWindow = binary.BigEndian.Uint32(b[32:])
  460. v.HandshakeType = binary.BigEndian.Uint32(b[36:])
  461. v.SRTSocketID = binary.BigEndian.Uint32(b[40:])
  462. v.SynCookie = binary.BigEndian.Uint32(b[44:])
  463. // Only support IPv4.
  464. v.PeerIP = net.IPv4(b[51], b[50], b[49], b[48])
  465. v.ExtraData = b[64:]
  466. return nil
  467. }
  468. func (v *SRTHandshakePacket) MarshalBinary() ([]byte, error) {
  469. b := make([]byte, 64+len(v.ExtraData))
  470. binary.BigEndian.PutUint16(b, uint16(v.ControlFlag)<<8|v.ControlType)
  471. binary.BigEndian.PutUint16(b[2:], v.SubType)
  472. binary.BigEndian.PutUint32(b[4:], v.AdditionalInfo)
  473. binary.BigEndian.PutUint32(b[8:], v.Timestamp)
  474. binary.BigEndian.PutUint32(b[12:], v.SocketID)
  475. binary.BigEndian.PutUint32(b[16:], v.Version)
  476. binary.BigEndian.PutUint16(b[20:], v.EncryptionField)
  477. binary.BigEndian.PutUint16(b[22:], v.ExtensionField)
  478. binary.BigEndian.PutUint32(b[24:], v.InitSequence)
  479. binary.BigEndian.PutUint32(b[28:], v.MTU)
  480. binary.BigEndian.PutUint32(b[32:], v.FlowWindow)
  481. binary.BigEndian.PutUint32(b[36:], v.HandshakeType)
  482. binary.BigEndian.PutUint32(b[40:], v.SRTSocketID)
  483. binary.BigEndian.PutUint32(b[44:], v.SynCookie)
  484. // Only support IPv4.
  485. ip := v.PeerIP.To4()
  486. b[48] = ip[3]
  487. b[49] = ip[2]
  488. b[50] = ip[1]
  489. b[51] = ip[0]
  490. if len(v.ExtraData) > 0 {
  491. copy(b[64:], v.ExtraData)
  492. }
  493. return b, nil
  494. }