Create a new socket with OS-specific parameters

    Try to set SO_REUSEPORT for BSD-flavored systems if it's an option.
    Catches errors if not.
429258
def new_socket():
    
    new_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    new_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    try:
        # noinspection PyUnresolvedReferences
        reuseport = socket.SO_REUSEPORT
    except AttributeError:
        pass
    else:
        try:
            new_sock.setsockopt(socket.SOL_SOCKET, reuseport, 1)
        except (OSError, socket.error) as err:
            # OSError on python 3, socket.error on python 2
            if err.errno != errno.ENOPROTOOPT:
                raise

    return new_sock
223850
def allocate_tcp_port():
    """"""
    # We want to bind() the socket but not listen(). Twisted (in
    # tcp.Port.createInternetSocket) would do several other things:
    # non-blocking, close-on-exec, and SO_REUSEADDR. We don't need
    # non-blocking because we never listen on it, and we don't need
    # close-on-exec because we close it right away. So just add SO_REUSEADDR.
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    if platformType == "posix" and sys.platform != "cygwin":
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(("127.0.0.1", 0))
    port = s.getsockname()[1]
    s.close()
    return port
490923
def start_server(port):
    '''  '''
    s = socket(AF_INET, SOCK_STREAM)
    s.settimeout(None)

    try:
        from socket import SO_REUSEPORT
        s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
    except ImportError:
        s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

    s.bind(('', port))
    pydev_log.info("Bound to port :%s", port)

    try:
        s.listen(1)
        newSock, _addr = s.accept()
        pydev_log.info("Connection accepted")
        # closing server socket is not necessary but we don't need it
        s.shutdown(SHUT_RDWR)
        s.close()
        return newSock

    except:
        pydev_log.exception("Could not bind to port: %s\n", port)
1371061
@Override
	public Socket createSocket(String host, int port) throws IOException,
			UnknownHostException {
		long start = System.currentTimeMillis();
		InetAddress addr = InetAddress.getByName(host);
		long end = System.currentTimeMillis();
		PerformanceLogger.noteElapsed("DNS:" + host, end - start);
		return new Socket(addr, port);
	}
1188621
function Socket(sio, options) {
  if (!(this instanceof Socket)) {
    return new Socket(sio, options);
  }

  EventEmitter.call(this);

  options = options || {};

  this.sio = sio;
  this.forceBase64 = !!options.forceBase64;
  this.streams = {};
  this.encoder = new parser.Encoder();
  this.decoder = new parser.Decoder();

  var eventName = exports.event;
  sio.on(eventName, bind(this, emit));
  sio.on(eventName + '-read', bind(this, '_onread'));
  sio.on(eventName + '-write', bind(this, '_onwrite'));
  sio.on(eventName + '-end', bind(this, '_onend'));
  sio.on(eventName + '-error', bind(this, '_onerror'));
  sio.on('error', bind(this, emit, 'error'));
  sio.on('disconnect', bind(this, '_ondisconnect'));

  this.encoder.on('stream', bind(this, '_onencode'));
  this.decoder.on('stream', bind(this, '_ondecode'));
}
690693
def _create_server(host, port):
    

    exc = socket.error("getaddrinfo returns an empty list")
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            # Create the listening socket
            sock = socket.socket(af, socktype, proto)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind(sa)
            sock.listen(1024)
            return sock

        except socket.error as exc:
            # Clean up after ourselves
            if sock is not None:
                sock.close()

    # Couldn't create a listening socket
    raise exc
334364
SocketChannel createSock() throws IOException {
        SocketChannel sock;
        sock = SocketChannel.open();
        sock.configureBlocking(false);
        sock.socket().setSoLinger(false, -1);
        sock.socket().setTcpNoDelay(true);
        return sock;
    }
731832
def create_socket():
    
    sock = socket.socket(PF_CAN, socket.SOCK_RAW, CAN_RAW)

    log.info('Created a socket')

    return sock
958071
def bind_unix_socket(self, bind_addr):
        """"""
        if IS_WINDOWS:
            """
            Trying to access socket.AF_UNIX under Windows
            causes an AttributeError.
            """
            raise ValueError(  # or RuntimeError?
                'AF_UNIX sockets are not supported under Windows.',
            )

        fs_permissions = 0o777  # TODO: allow changing mode

        try:
            # Make possible reusing the socket...
            os.unlink(self.bind_addr)
        except OSError:
            """
            File does not exist, which is the primary goal anyway.
            """

        sock = self.prepare_socket(
            bind_addr=bind_addr,
            family=socket.AF_UNIX, type=socket.SOCK_STREAM, proto=0,
            nodelay=self.nodelay, ssl_adapter=self.ssl_adapter,
        )

        try:
            """Linux way of pre-populating fs mode permissions."""
            # Allow everyone access the socket...
            os.fchmod(sock.fileno(), fs_permissions)
            FS_PERMS_SET = True
        except OSError:
            FS_PERMS_SET = False

        try:
            sock = self.bind_socket(sock, bind_addr)
        except socket.error:
            sock.close()
            raise

        bind_addr = self.resolve_real_bind_addr(sock)

        try:
            """FreeBSD/macOS pre-populating fs mode permissions."""
            if not FS_PERMS_SET:
                try:
                    os.lchmod(bind_addr, fs_permissions)
                except AttributeError:
                    os.chmod(bind_addr, fs_permissions, follow_symlinks=False)
                FS_PERMS_SET = True
        except OSError:
            pass

        if not FS_PERMS_SET:
            self.error_log(
                'Failed to set socket fs mode permissions',
                level=logging.WARNING,
            )

        self.bind_addr = bind_addr
        self.socket = sock
        return sock
339305
def _set_conf_sockets():
    
    if conf.use_bpf and not BSD:
        Interceptor.set_from_hook(conf, "use_bpf", False)
        raise ScapyInvalidPlatformException("BSD-like (OSX, *BSD...) only !")
    if conf.use_winpcapy and not WINDOWS:
        Interceptor.set_from_hook(conf, "use_winpcapy", False)
        raise ScapyInvalidPlatformException("Windows only !")
    # we are already in an Interceptor hook, use Interceptor.set_from_hook
    if conf.use_pcap or conf.use_dnet or conf.use_winpcapy:
        try:
            from scapy.arch.pcapdnet import L2pcapListenSocket, L2pcapSocket, \
                L3pcapSocket
        except ImportError:
            warning("No pcap provider available ! pcap won't be used")
            Interceptor.set_from_hook(conf, "use_winpcapy", False)
            Interceptor.set_from_hook(conf, "use_pcap", False)
        else:
            conf.L3socket = L3pcapSocket
            conf.L3socket6 = functools.partial(L3pcapSocket, filter="ip6")
            conf.L2socket = L2pcapSocket
            conf.L2listen = L2pcapListenSocket
            return
    if conf.use_bpf:
        from scapy.arch.bpf.supersocket import L2bpfListenSocket, \
            L2bpfSocket, L3bpfSocket
        conf.L3socket = L3bpfSocket
        conf.L3socket6 = functools.partial(L3bpfSocket, filter="ip6")
        conf.L2socket = L2bpfSocket
        conf.L2listen = L2bpfListenSocket
        return
    if LINUX:
        from scapy.arch.linux import L3PacketSocket, L2Socket, L2ListenSocket
        conf.L3socket = L3PacketSocket
        conf.L3socket6 = functools.partial(L3PacketSocket, filter="ip6")
        conf.L2socket = L2Socket
        conf.L2listen = L2ListenSocket
        return
    if WINDOWS:
        from scapy.arch.windows import _NotAvailableSocket
        from scapy.arch.windows.native import L3WinSocket, L3WinSocket6
        conf.L3socket = L3WinSocket
        conf.L3socket6 = L3WinSocket6
        conf.L2socket = _NotAvailableSocket
        conf.L2listen = _NotAvailableSocket
        return
    from scapy.supersocket import L3RawSocket
    from scapy.layers.inet6 import L3RawSocket6
    conf.L3socket = L3RawSocket
    conf.L3socket6 = L3RawSocket6
1103360
def ():
    """"""

    # create a socket for recording layer 2, 3 and 4 frames
    s = None
    try:
        log.info("Creating l234 socket")
        s = socket.socket(socket.AF_PACKET,
                          socket.SOCK_RAW,
                          socket.ntohs(0x0003))
    except socket.error as msg:
        log.error(("Socket could not be created ex={}")
                  .format(msg))
    return s
113351
def create_connction(host, port, protocol):
    
    ai_list = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM)
    for (family, socktype, proto, canon, sockaddr) in ai_list:
        sock = socket.socket(family, socktype)
        # WRAP SOCKET
        if port == 443:
            sock = ssl.wrap_socket(sock, ssl_version=protocol)
        sock.connect(sockaddr)
        return sock
903784
def start(self):
        '''
        
        '''
        log.debug('Creating the TCP server')
        if ':' in self.address:
            self.skt = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        else:
            self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if self.reuse_port:
            self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            if hasattr(socket, 'SO_REUSEPORT'):
                self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            else:
                log.error('SO_REUSEPORT not supported')
        try:
            self.skt.bind((self.address, int(self.port)))
        except socket.error as msg:
            error_string = 'Unable to bind to port {} on {}: {}'.format(self.port, self.address, msg)
            log.error(error_string, exc_info=True)
            raise BindException(error_string)
        log.debug('Accepting max %d parallel connections', self.max_clients)
        self.skt.listen(self.max_clients)
        self.thread_serve = threading.Thread(target=self._serve_clients)
        self.thread_serve.start()
1205012
def new_port():
    """"""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
    for i in range(12042, 16042):
        try:
            s.bind(('127.0.0.1', i))
            s.close()
            return i
        except socket.error:
            pass
    raise Exception('No local port available')
765606
def client(addr):
        """"""
        success = False
        while not success:
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                sock.connect(addr)
                success = True
            except socket.error as err:
                sock.close()
        talk = SocketTalk(sock)
        return talk
1068976
def _create_socket(self, socket_family):
        
        sock = socket.socket(socket_family, socket.SOCK_STREAM, 0)
        sock.settimeout(self._parameters['timeout'] or None)
        if self.use_ssl:
            if not compatibility.SSL_SUPPORTED:
                raise AMQPConnectionError(
                    'Python not compiled with support for TLSv1 or higher'
                )
            sock = self._ssl_wrap_socket(sock)
        return sock
158736
def create_client_socket(self, config):
		
		client_socket = WUDPNetworkNativeTransport.create_client_socket(self, config)
		client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
		return client_socket