1 /** 2 * 3 * Licensed to the Apache Software Foundation (ASF) under one 4 * or more contributor license agreements. See the NOTICE file 5 * distributed with this work for additional information 6 * regarding copyright ownership. The ASF licenses this file 7 * to you under the Apache License, Version 2.0 (the 8 * "License"); you may not use this file except in compliance 9 * with the License. You may obtain a copy of the License at 10 * 11 * http://www.apache.org/licenses/LICENSE-2.0 12 * 13 * Unless required by applicable law or agreed to in writing, software 14 * distributed under the License is distributed on an "AS IS" BASIS, 15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 * See the License for the specific language governing permissions and 17 * limitations under the License. 18 */ 19 package org.apache.hadoop.hbase.util; 20 21 import java.net.InetSocketAddress; 22 23 import org.apache.hadoop.hbase.classification.InterfaceAudience; 24 25 /** 26 * Utility for network addresses, resolving and naming. 27 */ 28 @InterfaceAudience.Private 29 public class Addressing { 30 public static final String VALID_PORT_REGEX = "[\\d]+"; 31 public static final String HOSTNAME_PORT_SEPARATOR = ":"; 32 33 /** 34 * @param hostAndPort Formatted as <code><hostname> ':' <port></code> 35 * @return An InetSocketInstance 36 */ 37 public static InetSocketAddress createInetSocketAddressFromHostAndPortStr( 38 final String hostAndPort) { 39 return new InetSocketAddress(parseHostname(hostAndPort), parsePort(hostAndPort)); 40 } 41 42 /** 43 * @param hostname Server hostname 44 * @param port Server port 45 * @return Returns a concatenation of <code>hostname</code> and 46 * <code>port</code> in following 47 * form: <code><hostname> ':' <port></code>. For example, if hostname 48 * is <code>example.org</code> and port is 1234, this method will return 49 * <code>example.org:1234</code> 50 */ 51 public static String createHostAndPortStr(final String hostname, final int port) { 52 return hostname + HOSTNAME_PORT_SEPARATOR + port; 53 } 54 55 /** 56 * @param hostAndPort Formatted as <code><hostname> ':' <port></code> 57 * @return The hostname portion of <code>hostAndPort</code> 58 */ 59 public static String parseHostname(final String hostAndPort) { 60 int colonIndex = hostAndPort.lastIndexOf(HOSTNAME_PORT_SEPARATOR); 61 if (colonIndex < 0) { 62 throw new IllegalArgumentException("Not a host:port pair: " + hostAndPort); 63 } 64 return hostAndPort.substring(0, colonIndex); 65 } 66 67 /** 68 * @param hostAndPort Formatted as <code><hostname> ':' <port></code> 69 * @return The port portion of <code>hostAndPort</code> 70 */ 71 public static int parsePort(final String hostAndPort) { 72 int colonIndex = hostAndPort.lastIndexOf(HOSTNAME_PORT_SEPARATOR); 73 if (colonIndex < 0) { 74 throw new IllegalArgumentException("Not a host:port pair: " + hostAndPort); 75 } 76 return Integer.parseInt(hostAndPort.substring(colonIndex + 1)); 77 } 78 }