Sanitizes a TCP/IP port number.

 @param port [#to_i, #to_s] the port number to sanitize
 @return [Integer, nil] the sanitized value or +nil+ on error
973490
def valid_port(port)
      port_number = port.to_s.to_i(10) if /\A[0-9]+\z/ =~ port.to_s
      port_number if (1...2**16).cover? port_number
    end
874246
def ports_as_list(port_str):
    
    if not port_str:
        LOGGER.info("Invalid port value")
        return [None, None]

    if ports_str_check_failed(port_str):
        LOGGER.info("{0}: Port list malformed.")
        return [None, None]

    tcp_list = list()
    udp_list = list()
    ports = port_str.replace(' ', '')
    b_tcp = ports.find("T")
    b_udp = ports.find("U")

    if ports[b_tcp - 1] == ',':
        ports = ports[:b_tcp - 1] + ports[b_tcp:]
    if ports[b_udp - 1] == ',':
        ports = ports[:b_udp - 1] + ports[b_udp:]
    ports = port_str_arrange(ports)

    tports = ''
    uports = ''
    # TCP ports listed first, then UDP ports
    if b_udp != -1 and b_tcp != -1:
        tports = ports[ports.index('T:') + 2:ports.index('U:')]
        uports = ports[ports.index('U:') + 2:]
    # Only UDP ports
    elif b_tcp == -1 and b_udp != -1:
        uports = ports[ports.index('U:') + 2:]
    # Only TCP ports
    elif b_udp == -1 and b_tcp != -1:
        tports = ports[ports.index('T:') + 2:]
    else:
        tports = ports

    if tports:
        for port in tports.split(','):
            if '-' in port:
                tcp_list.extend(port_range_expand(port))
            else:
                tcp_list.append(int(port))
        tcp_list.sort()
    if uports:
        for port in uports.split(','):
            if '-' in port:
                udp_list.extend(port_range_expand(port))
            else:
                udp_list.append(int(port))
        udp_list.sort()

    return (tcp_list, udp_list)
231917
def get_ip_ports(state = nil)
      begin
        @port.get_ip_ports(state)
      rescue => ex
        Util.log_exception(ex, caller_locations(1, 1)[0].label)
        raise ex
      end
    end
593689
def get_host_port(self, container_port, proto='tcp', index=0):
        
        port_spec = '{}/{}'.format(container_port, proto)
        return self._host_port(port_spec, index)
1079092
public static String sanitizeDefaultPort(String url) {
        int afterSchemeIndex = url.indexOf("://");
        if(afterSchemeIndex < 0) {
            return url;
        }
        String scheme = url.substring(0, afterSchemeIndex);
        int fromIndex = scheme.length() + 3;
        //Let's see if it is an IPv6 Address
        int ipv6StartIndex = url.indexOf('[', fromIndex);
        if (ipv6StartIndex > 0) {
            fromIndex = url.indexOf(']', ipv6StartIndex);
        }
        int portIndex = url.indexOf(':', fromIndex);
        if(portIndex >= 0) {
            int port = Integer.parseInt(url.substring(portIndex + 1));
            if(isDefaultPort(port, scheme)) {
                return url.substring(0, portIndex);
            }
        }
        return url;
    }
280806
def detect_port(port):
    ''''''
    socket_test = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        socket_test.connect(('127.0.0.1', int(port)))
        socket_test.close()
        return True
    except:
        return False
1291225
public final UdpServer port(int port) {
		return bootstrap(b -> b.localAddress(getHost(b), port));
	}
1035937
def address(addr):
    

    if ':' in addr:
        # Using rpartition here means we should be able to support
        # IPv6, but only with a strict syntax
        host, _sep, port = addr.rpartition(':')

        # Convert the port to a number
        try:
            port = int(port)
        except ValueError:
            raise ValueError("invalid port number %r" % port)

        addr = (host, port)

    return addr
612945
def url_to_host_port(url, port=None):
    
    if not url.startswith('http://') and not url.startswith('https://'):
        url = 'http://' + url

    if not port:
        port = RPC_SERVER_PORT

    urlinfo = urllib2.urlparse.urlparse(url)
    hostport = urlinfo.netloc

    parts = hostport.split('@')
    if len(parts) > 2:
        return None, None

    if len(parts) == 2:
        hostport = parts[1]

    parts = hostport.split(':')
    if len(parts) > 2:
        return None, None

    if len(parts) == 2:
        try:
            port = int(parts[1])
            assert 0 < port and port < 65535, 'Invalid port'
        except TypeError:
            return None, None

    return parts[0], port
647677
def tcpip(self, port: int or str = 5555) -> None:
        ''''''
        self._execute('-s', self.device_sn, 'tcpip', str(port))
666659
def is_numeric_port (portstr):
    
    if portstr.isdigit():
        port = int(portstr)
        # 65536 == 2**16
        if 0 < port < 65536:
            return port
    return False
873692
function nextPort(port) {
  if (!port) {
    return 8000;
  }

  //
  // Find the next port that we are not supposed to ignore or cause errors on
  //
  var unavailable = carapace.ports.ignore.concat(carapace.ports.throw);
  do {
    port = port + 1;
  } while (unavailable.indexOf(port) !== -1);

  return port;
}
176688
private function formatPort($port = null): ?int
    {
        if (null === $port || '' === $port) {
            return null;
        }

        if (!is_int($port) && !(is_string($port) && 1 === preg_match('/^\d*$/', $port))) {
            throw new SyntaxError(sprintf('The port `%s` is invalid', $port));
        }

        $port = (int) $port;
        if (0 > $port) {
            throw new SyntaxError(sprintf('The port `%s` is invalid', $port));
        }

        $defaultPort = self::SCHEME_DEFAULT_PORT[$this->scheme] ?? null;
        if ($defaultPort === $port) {
            return null;
        }

        return $port;
    }
50805
def _validate_single_port_string(port):
    
    if ' ' not in port or len(port.split(' ')) != 2:
        raise ValueError(
            "Port '{}' should have exactly one space in it".format(port)
        )
    (external, internal) = port.split(' ')
    try:
        external = int(external)
    except ValueError:
        raise ValueError(
            "Port '{}' external port isn't an int".format(port)
        )
    if ':' not in internal:
        raise ValueError(
            "Port '{}' local address should be 'IP:port'".format(port)
        )
    if not internal.startswith('unix:'):
        ip, localport = internal.split(':')
        if ip != 'localhost' and not _is_non_public_numeric_address(ip):
            raise ValueError(
                "Port '{}' internal IP '{}' should be a local "
                "address".format(port, ip)
            )
1270648
def port_number_range(prange):
    
    # first, try it as a normal port number
    try:
        return port_number(prange)
    except ValueError:
        pass
    # then, consider it as a range with the format "x-y" and expand it
    try:
        bounds = list(map(int, re.match(r'^(\d+)\-(\d+)$', prange).groups()))
        if bounds[0] > bounds[1]:
            raise AttributeError()
    except (AttributeError, TypeError):
        raise ValueError("Bad port number range")
    return list(range(bounds[0], bounds[1] + 1))
845002
def _convert_port_bindings(self, value):
        
        converted = {}

        if not value:
            return converted

        if isinstance(value, list):
            value = self._convert_port_bindings_from_list(value)

        if isinstance(value, dict):
            for port_protocol, host_bindings in six.iteritems(value):
                if '/' in port_protocol:
                    port, protocol = port_protocol.split('/')

                    if protocol not in ('tcp', 'udp'):
                        raise ValueError('only supported protocols are tcp and udp. {0} was passed.'.format(protocol))
                else:
                    port_protocol = "{0}/tcp".format(port_protocol)

                converted[port_protocol] = []

                if isinstance(host_bindings, list):
                    for host_binding in host_bindings:
                        if isinstance(host_binding, dict):
                            if "host_port" not in host_binding:
                                raise ValueError("host_port must be provided.")

                            if 'host_ip' not in host_binding:
                                host_binding['host_ip'] = ''

                            converted[port_protocol].append(host_binding)
                        else:
                            raise TypeError("The host binding information must be a dict.")
                else:
                    raise TypeError("The host binding information in port bindings must be in a list.")

        return converted
1293734
private function filterPort($port)
    {
        if ($port === null) {
            return $port;
        }

        if (!preg_match('#^[0-9]+$#', (string) $port)) {
            throw new \InvalidArgumentException(sprintf('Invalid port "%s".', $port));
        }

        return (int) $port;
    }