Source file src/net/sockopt_posix.go

     1  // Copyright 2009 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  
     5  //go:build unix || windows
     6  
     7  package net
     8  
     9  import (
    10  	"runtime"
    11  	"syscall"
    12  )
    13  
    14  // Boolean to int.
    15  func boolint(b bool) int {
    16  	if b {
    17  		return 1
    18  	}
    19  	return 0
    20  }
    21  
    22  func interfaceToIPv4Addr(ifi *Interface) (IP, error) {
    23  	if ifi == nil {
    24  		return IPv4zero, nil
    25  	}
    26  	ifat, err := ifi.Addrs()
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  	for _, ifa := range ifat {
    31  		switch v := ifa.(type) {
    32  		case *IPAddr:
    33  			if v.IP.To4() != nil {
    34  				return v.IP, nil
    35  			}
    36  		case *IPNet:
    37  			if v.IP.To4() != nil {
    38  				return v.IP, nil
    39  			}
    40  		}
    41  	}
    42  	return nil, errNoSuchInterface
    43  }
    44  
    45  func setReadBuffer(fd *netFD, bytes int) error {
    46  	err := fd.pfd.SetsockoptInt(syscall.SOL_SOCKET, syscall.SO_RCVBUF, bytes)
    47  	runtime.KeepAlive(fd)
    48  	return wrapSyscallError("setsockopt", err)
    49  }
    50  
    51  func setWriteBuffer(fd *netFD, bytes int) error {
    52  	err := fd.pfd.SetsockoptInt(syscall.SOL_SOCKET, syscall.SO_SNDBUF, bytes)
    53  	runtime.KeepAlive(fd)
    54  	return wrapSyscallError("setsockopt", err)
    55  }
    56  
    57  func setKeepAlive(fd *netFD, keepalive bool) error {
    58  	err := fd.pfd.SetsockoptInt(syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, boolint(keepalive))
    59  	runtime.KeepAlive(fd)
    60  	return wrapSyscallError("setsockopt", err)
    61  }
    62  
    63  func setLinger(fd *netFD, sec int) error {
    64  	var l syscall.Linger
    65  	if sec >= 0 {
    66  		l.Onoff = 1
    67  		l.Linger = int32(sec)
    68  	} else {
    69  		l.Onoff = 0
    70  		l.Linger = 0
    71  	}
    72  	err := fd.pfd.SetsockoptLinger(syscall.SOL_SOCKET, syscall.SO_LINGER, &l)
    73  	runtime.KeepAlive(fd)
    74  	return wrapSyscallError("setsockopt", err)
    75  }
    76  

View as plain text