socket.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2017 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package socket provides a portable interface for socket system
  5. // calls.
  6. package socket // import "golang.org/x/net/internal/socket"
  7. import "errors"
  8. // An Option represents a sticky socket option.
  9. type Option struct {
  10. Level int // level
  11. Name int // name; must be equal or greater than 1
  12. Len int // length of value in bytes; must be equal or greater than 1
  13. }
  14. // Get reads a value for the option from the kernel.
  15. // It returns the number of bytes written into b.
  16. func (o *Option) Get(c *Conn, b []byte) (int, error) {
  17. if o.Name < 1 || o.Len < 1 {
  18. return 0, errors.New("invalid option")
  19. }
  20. if len(b) < o.Len {
  21. return 0, errors.New("short buffer")
  22. }
  23. return o.get(c, b)
  24. }
  25. // GetInt returns an integer value for the option.
  26. //
  27. // The Len field of Option must be either 1 or 4.
  28. func (o *Option) GetInt(c *Conn) (int, error) {
  29. if o.Len != 1 && o.Len != 4 {
  30. return 0, errors.New("invalid option")
  31. }
  32. var b []byte
  33. var bb [4]byte
  34. if o.Len == 1 {
  35. b = bb[:1]
  36. } else {
  37. b = bb[:4]
  38. }
  39. n, err := o.get(c, b)
  40. if err != nil {
  41. return 0, err
  42. }
  43. if n != o.Len {
  44. return 0, errors.New("invalid option length")
  45. }
  46. if o.Len == 1 {
  47. return int(b[0]), nil
  48. }
  49. return int(NativeEndian.Uint32(b[:4])), nil
  50. }
  51. // Set writes the option and value to the kernel.
  52. func (o *Option) Set(c *Conn, b []byte) error {
  53. if o.Name < 1 || o.Len < 1 {
  54. return errors.New("invalid option")
  55. }
  56. if len(b) < o.Len {
  57. return errors.New("short buffer")
  58. }
  59. return o.set(c, b)
  60. }
  61. // SetInt writes the option and value to the kernel.
  62. //
  63. // The Len field of Option must be either 1 or 4.
  64. func (o *Option) SetInt(c *Conn, v int) error {
  65. if o.Len != 1 && o.Len != 4 {
  66. return errors.New("invalid option")
  67. }
  68. var b []byte
  69. if o.Len == 1 {
  70. b = []byte{byte(v)}
  71. } else {
  72. var bb [4]byte
  73. NativeEndian.PutUint32(bb[:o.Len], uint32(v))
  74. b = bb[:4]
  75. }
  76. return o.set(c, b)
  77. }