Initializes the datagram socket associated with this end point.

@param vc
@return DatagramSocket
429513
protected DatagramSocket initDatagramSocket(VirtualConnection vc) throws IOException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Create new DatagramSocket: " + vc);
        }
        UDPChannelConfiguration channelConfig = udpChannel.getConfig();
        InetSocketAddress address = null;

        if (localBindAddress != null) {
            if (localBindAddress.equals("*")) {
                localBindAddress = "0.0.0.0";
            }
            address = new InetSocketAddress(localBindAddress, localBindPort);

            if (address.isUnresolved()) {
                String displayableHostName = channelConfig.getHostname();
                if (displayableHostName == null) {
                    displayableHostName = "*";
                }
                Tr.error(tc, "CWUDP0004E", new Object[] { channelConfig.getExternalName(), displayableHostName, String.valueOf(channelConfig.getPort()) });
                throw (new IOException("local address unresolved"));
            }
        }

        datagramChannel = DatagramChannel.open();
        DatagramSocket datagramSocket = datagramChannel.socket();

        // never reuse - only one app can have the port open
        datagramSocket.setReuseAddress(false);
        datagramChannel.configureBlocking(false);

        // receieve buffer size for sockets is set on datagramSocket,
        // send buffer size is set on individual sockets

        if ((channelConfig.getReceiveBufferSize() >= UDPConfigConstants.RECEIVE_BUFFER_SIZE_MIN)
            && (channelConfig.getReceiveBufferSize() <= UDPConfigConstants.RECEIVE_BUFFER_SIZE_MAX)) {
            int size = datagramSocket.getReceiveBufferSize();
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "setting receive buffer to size " + channelConfig.getReceiveBufferSize());
            }
            try {
                datagramSocket.setReceiveBufferSize(channelConfig.getReceiveBufferSize());
                int size1 = datagramSocket.getReceiveBufferSize();
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    if (size == size1) {
                        Tr.debug(tc, "setting receive buffer had no effect, still the same size ");
                    }
                }
            } catch (SocketException e) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Caught SocketException " + e.getMessage() + " while trying to setReceiveBufferSize to " + channelConfig.getReceiveBufferSize());
                }
            } catch (IllegalArgumentException e) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Caught IllegalArgumentException " + e.getMessage() + " while trying to setReceiveBufferSize to " + channelConfig.getReceiveBufferSize());
                }
            }
        }
        if ((channelConfig.getSendBufferSize() >= UDPConfigConstants.SEND_BUFFER_SIZE_MIN) && (channelConfig.getSendBufferSize() <= UDPConfigConstants.SEND_BUFFER_SIZE_MAX)) {
            int size = datagramSocket.getSendBufferSize();
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "setting send buffer to size " + channelConfig.getSendBufferSize());
            }
            try {
                datagramSocket.setSendBufferSize(channelConfig.getSendBufferSize());
                int size1 = datagramSocket.getSendBufferSize();
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    if (size == size1) {
                        Tr.debug(tc, "setting send buffer had no effect, still the same size ");
                    }
                }
            } catch (SocketException e) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Caught SocketException " + e.getMessage() + " while trying to setSendBufferSize to " + channelConfig.getSendBufferSize());
                }
            } catch (IllegalArgumentException e) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Caught IllegalArgumentException " + e.getMessage() + " while trying to setSendBufferSize to " + channelConfig.getSendBufferSize());
                }
            }
        }
        try {
            datagramSocket.bind(address);
            selectorMonitor.setChannel(datagramChannel, this);
        } catch (IOException ioe) {
            String displayableHostName = channelConfig.getHostname();
            if (displayableHostName == null) {
                displayableHostName = "*";
            }
            Tr.error(tc, "CWUDP0005E", new Object[] { channelConfig.getExternalName(), displayableHostName, String.valueOf(channelConfig.getPort()) });
            throw new IOException(ioe.getMessage());
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "new ServerSocket successfully created");
        }

        return datagramChannel.socket();
    }
1317469
protected ByteBuf allocateBuffer(
        ChannelHandlerContext ctx,
        @SuppressWarnings("unused") AddressedEnvelope<DnsResponse, InetSocketAddress> msg) throws Exception {
        return ctx.alloc().ioBuffer(1024);
    }
18022
public static TcpClient<ByteBuf, ByteBuf> newClient(String host, int port) {
        return newClient(new InetSocketAddress(host, port));
    }
710476
@Override
    public ConnectionLink getConnectionLink(VirtualConnection vc) {
        HttpDispatcherLink link = (HttpDispatcherLink) vc.getStateMap().get(HttpDispatcherLink.LINK_ID);
        if (null == link) {
            link = new HttpDispatcherLink();
            link.init(vc, this);
        }
        return link;
    }
1190394
static DatagramSocketImpl createDatagramSocketImpl(boolean isMulticast /*unused on unix*/)
        throws SocketException {
        if (prefixImplClass != null) {
            try {
                return (DatagramSocketImpl)prefixImplClass.newInstance();
            } catch (Exception e) {
                throw new SocketException("can't instantiate DatagramSocketImpl");
            }
        } else {
            return new java.net.PlainDatagramSocketImpl();
        }
    }
526114
def receive_datagram(self):
        
        logger.debug("Start receiver Thread")
        while not self.stopped.isSet():
            self._socket.settimeout(0.1)
            try:
                datagram, addr = self._socket.recvfrom(1152)
            except socket.timeout:  # pragma: no cover
                continue
            except Exception as e:  # pragma: no cover
                if self._cb_ignore_read_exception is not None and isinstance(self._cb_ignore_read_exception, collections.Callable):
                    if self._cb_ignore_read_exception(e, self):
                        continue
                return
            else:  # pragma: no cover
                if len(datagram) == 0:
                    logger.debug("Exiting receiver Thread due to orderly shutdown on server end")
                    return

            serializer = Serializer()

            try:
                host, port = addr
            except ValueError:
                host, port, tmp1, tmp2 = addr

            source = (host, port)

            message = serializer.deserialize(datagram, source)

            if isinstance(message, Response):
                logger.debug("receive_datagram - " + str(message))
                transaction, send_ack = self._messageLayer.receive_response(message)
                if transaction is None:  # pragma: no cover
                    continue
                self._wait_for_retransmit_thread(transaction)
                if send_ack:
                    self._send_ack(transaction)
                self._blockLayer.receive_response(transaction)
                if transaction.block_transfer:
                    self._send_block_request(transaction)
                    continue
                elif transaction is None:  # pragma: no cover
                    self._send_rst(transaction)
                    return
                self._observeLayer.receive_response(transaction)
                if transaction.notification:  # pragma: no cover
                    ack = Message()
                    ack.type = defines.Types['ACK']
                    ack = self._messageLayer.send_empty(transaction, transaction.response, ack)
                    self.send_datagram(ack)
                    self._callback(transaction.response)
                else:
                    self._callback(transaction.response)
            elif isinstance(message, Message):
                self._messageLayer.receive_empty(message)

        logger.debug("Exiting receiver Thread due to request")
1329894
@Override
	public void prepareSender() throws LifecycleException {

		if (host == null || port == null) {
			throw new LifecycleException("Host and port for " + this.getClass().getSimpleName() + " output can't be null");
		}

		try {
			this.dgSocket = new DatagramSocket();
			this.address = new InetSocketAddress(host, port);
		} catch (SocketException sockExc) {
			log.error("Failed to create a datagram socket", sockExc);
			throw new LifecycleException(sockExc);
		}
	}
1182564
public static WebsocketClientTransport create(InetSocketAddress address) {
    Objects.requireNonNull(address, "address must not be null");

    TcpClient client = TcpClient.create().addressSupplier(() -> address);
    return create(client);
  }
1181394
public EpollSocketChannelConfig setSoBusyPoll(int loopMicros) {
        try {
            ((EpollSocketChannel) channel).socket.setSoBusyPoll(loopMicros);
            return this;
        } catch (IOException e) {
            throw new ChannelException(e);
        }
    }
675239
public static FastForward setup(InetAddress addr, int port) throws SocketException {
        final DatagramSocket socket = new DatagramSocket();
        return new FastForward(addr, port, socket);
    }
280355
protected void readProxyResponse(VirtualConnection inVC) {

        int size = 1;
        if (!this.isProxyResponseValid) {
            // we need at least 12 bytes for the first line
            size = 12;
        }
        if (connLink.isAsyncConnect()) {
            VirtualConnection vcRC = connLink.getReadInterface().read(size, this.proxyReadCB, false, TCPRequestContext.USE_CHANNEL_TIMEOUT);
            if (null != vcRC) {
                this.proxyReadCB.complete(vcRC, connLink.getReadInterface());
            }
        } else {
            try {
                connLink.getReadInterface().read(size, TCPRequestContext.USE_CHANNEL_TIMEOUT);
            } catch (IOException x) {
                // no FFDC required
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "could not complete proxy handshake, read request failed");
                }
                releaseProxyReadBuffer();
                connLink.connectFailed(x);
            }
        }
    }
184382
@Override
  public StreamImpl stream()
    throws IOException
  {
    if (_channelStream == null) {
      _channelStream = new SocketChannelStream();
    }
    
    if (_sslSocket == null) {
      _channelStream.init(_channel);
      _streamImpl = _channelStream;
    }
    else {
      if (_sslStream == null) {
        _sslStream = new SocketStream();
      }
      
      _sslStream.init(_sslSocket);
      _streamImpl = _sslStream;
    }

    return _streamImpl;
  }
1016391
private static void bind(final NioDatagramChannel channel,
                             final ChannelFuture future, final InetSocketAddress address) {
        boolean bound = false;
        boolean started = false;
        try {
            // First bind the DatagramSocket the specified port.
            channel.getDatagramChannel().socket().bind(address);
            bound = true;

            future.setSuccess();
            fireChannelBound(channel, address);

            channel.worker.register(channel, null);
            started = true;
        } catch (final Throwable t) {
            future.setFailure(t);
            fireExceptionCaught(channel, t);
        } finally {
            if (!started && bound) {
                close(channel, future);
            }
        }
    }
64362
public ChannelTermination setup(ChannelData runtimeConfig, TCPChannelConfiguration tcpConfig, TCPChannelFactory factory) throws ChannelException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "setup");
        }
        this.channelFactory = factory;
        this.channelData = runtimeConfig;
        this.channelName = runtimeConfig.getName();
        this.externalName = runtimeConfig.getExternalName();
        this.config = tcpConfig;

        for (int i = 0; i < this.inUse.length; i++) {
            this.inUse[i] = new ConcurrentLinkedQueue<TCPConnLink>();
        }

        this.vcFactory = ChannelFrameworkFactory.getChannelFramework().getInboundVCFactory();

        this.alists = AccessLists.getInstance(this.config);

        if (this.config.isInbound() && acceptReqProcessor.get() == null) {
            acceptReqProcessor = StaticValue.mutateStaticValue(acceptReqProcessor, new Callable<NBAccept>() {
                @Override
                public NBAccept call() throws Exception {
                    return new NBAccept(TCPChannel.this.config);
                }

            });
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "setup");
        }
        return null;
    }
23335
private SocketIOChannel create(InetSocketAddress localAddress, TCPConnLink tcpConnLink) throws IOException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "create");
        }

        SocketIOChannel ioSocket = tcpChannel.createOutboundSocketIOChannel();
        Socket socket = ioSocket.getSocket();
        TCPChannelConfiguration tcpConfig = this.tcpChannel.getConfig();

        socket.setReuseAddress(tcpConfig.getSoReuseAddress());

        if ((tcpConfig.getReceiveBufferSize() >= RECEIVE_BUFFER_SIZE_MIN) && (tcpConfig.getReceiveBufferSize() <= RECEIVE_BUFFER_SIZE_MAX)) {
            socket.setReceiveBufferSize(tcpConfig.getReceiveBufferSize());
        }

        if ((tcpConfig.getSendBufferSize() >= SEND_BUFFER_SIZE_MIN) && (tcpConfig.getSendBufferSize() <= SEND_BUFFER_SIZE_MAX)) {
            socket.setSendBufferSize(tcpConfig.getSendBufferSize());
        }

        // need this check, or else the getLocalAddress call will return all zeroes
        // if we bind with a null localAddress here
        if (localAddress != null) {
            try {
                socket.bind(localAddress);

                InetAddress ia = localAddress.getAddress();
                if (ia != null) {
                    ConnectionDescriptor cd = tcpConnLink.getVirtualConnection().getConnectionDescriptor();

                    if (cd != null) {
                        cd.setAddrs(null, ia);
                    } else {
                        ConnectionDescriptorImpl cdi = new ConnectionDescriptorImpl(null, ia);
                        tcpConnLink.getVirtualConnection().setConnectionDescriptor(cdi);
                    }

                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "bound connection: " + tcpConnLink.getVirtualConnection().getConnectionDescriptor());
                    }
                }

            } catch (IOException ioe) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Bind error making outbound connection " + ioe);
                }

                if (socket != null) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Socket closed on bind exception.");
                    }
                    socket.close();
                }

                FFDCFilter.processException(ioe, getClass().getName(), "create", this);
                throw ioe;
            }
        }

        if (tcpConfig.getSoLinger() >= 0) {
            socket.setSoLinger(true, tcpConfig.getSoLinger());
        } else {
            socket.setSoLinger(false, 0);
        }

        socket.setKeepAlive(tcpConfig.getKeepAlive());

        socket.setTcpNoDelay(tcpConfig.getTcpNoDelay());

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Socket created, local port: " + socket.getLocalPort());
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "create");
        }

        return ioSocket;
    }
1207733
@Override
    public ConnectionLink getConnectionLink(VirtualConnection vc) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "getConnectionLink");
        }

        // add this new connection link to the next in-use list based on
        // the atomic index, the extra add/mod handles the negative values
        int index = ((this.inUseIndex.getAndIncrement() % SIZE_IN_USE) + SIZE_IN_USE) % SIZE_IN_USE;

        TCPConnLink connLink = new TCPConnLink(vc, this, this.config, index);
        this.inUse[index].add(connLink);

        // assign default ConnectionType and unique ConnectionHandle to new inbound
        // connection
        // ConnectionType may seem redundant, but is used on some platforms to
        // identify
        // more than just inbound/outbound flow.
        ConnectionType.setDefaultVCConnectionType(vc);
        ConnectionHandle.getConnectionHandle(vc);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "getConnectionLink: " + connLink);
        }
        return connLink;
    }
705027
private DatagramSocket initRandomPortSocket() {
        int bindRetries = 5;
        int currentlyTriedPort = getRandomPortNumber(JainSipUtils.MIN_PORT_NUMBER, JainSipUtils.MAX_PORT_NUMBER);

        DatagramSocket resultSocket = null;
        // we'll first try to bind to a random port. if this fails we'll try
        // again (bindRetries times in all) until we find a free local port.
        for (int i = 0; i < bindRetries; i++) {
            try {
                resultSocket = new DatagramSocket(currentlyTriedPort);
                // we succeeded - break so that we don't try to bind again
                break;
            } catch (SocketException exc) {
                if (exc.getMessage().indexOf("Address already in use") == -1) {
                    logger.fatal("An exception occurred while trying to create" + "a local host discovery socket.", exc);
                    return null;
                }
                // port seems to be taken. try another one.
                logger.debug("Port " + currentlyTriedPort + " seems in use.");
                currentlyTriedPort = getRandomPortNumber(JainSipUtils.MIN_PORT_NUMBER, JainSipUtils.MAX_PORT_NUMBER);
                logger.debug("Retrying bind on port " + currentlyTriedPort);
            }
        }

        return resultSocket;
    }