/* JFlexiPix - Java implementation of FlexiPix output library
 *
 * Copyright 2010-2011 Stefan Schuermans <stefan schuermans info>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package org.blinkenarea.JFlexiPix;

import java.net.*;
import java.util.regex.*;

/// parser for a socket address
class AddrParser
{
  /**
   * @brief parse address
   * @param[in] text address in text form ("host:port")
   * @return address or null
   */
  static InetSocketAddress parseAddr(String text)
  {
    Pattern pattern;
    Matcher matcher;
    String strHost, strPort;
    InetAddress host;
    int port;

    // split text into host and port
    pattern = Pattern.compile("^([-.a-zA-Z0-9_]+):([0-9]+)$");
    matcher = pattern.matcher(text);
    if (!matcher.find())
      return null;
    strHost = matcher.group(1);
    strPort = matcher.group(2);

    // parse host
    try {
      host = InetAddress.getByName(strHost);
    } catch (UnknownHostException e) {
      return null;
    }

    // parse port
    try {
      port = Integer.parseInt(strPort);
    } catch (NumberFormatException e) {
      return null;
    }

    return new InetSocketAddress(host, port);
  }
}

