Socket Address Encoder : Socket « Network Protocol « Java

Socket Address Encoder

 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.

import java.util.StringTokenizer;

 * <strong>Internal class, do not use directly.</strong>
 * Encodes and decodes socket addresses (IP and port) from and to the format
 * used with for example the PORT and PASV command
 * @author The Apache MINA Project (
public class SocketAddressEncoder {

    private static int convertAndValidateNumber(String s) {
        int i = Integer.parseInt(s);
        if (i < 0) {
            throw new IllegalArgumentException("Token can not be less than 0");
        } else if (i > 255) {
            throw new IllegalArgumentException(
                    "Token can not be larger than 255");

        return i;

    public static InetSocketAddress decode(String str)
            throws UnknownHostException {
        StringTokenizer st = new StringTokenizer(str, ",");
        if (st.countTokens() != 6) {
            throw new Exception("Illegal amount of tokens");

        StringBuffer sb = new StringBuffer();
        try {
        } catch (IllegalArgumentException e) {
            throw new Exception(e.getMessage());

        InetAddress dataAddr = InetAddress.getByName(sb.toString());

        // get data server port
        int dataPort = 0;
        try {
            int hi = convertAndValidateNumber(st.nextToken());
            int lo = convertAndValidateNumber(st.nextToken());
            dataPort = (hi << 8) | lo;
        } catch (IllegalArgumentException ex) {
            throw new Exception("Invalid data port: " + str);

        return new InetSocketAddress(dataAddr, dataPort);

    public static String encode(InetSocketAddress address) {
        InetAddress servAddr = address.getAddress();
        int servPort = address.getPort();
        return servAddr.getHostAddress().replace('.', ',') + ','
                + (servPort >> 8) + ',' + (servPort & 0xFF);



Related examples in the same category

1.Create a socket without a timeout
2.Create a socket with a timeout
3.Demonstrate Sockets.
4.Socket connection and concurrent package
5.XML based message
6.ObjectInputStream and ObjectOutputStream from Socket
7.ServerSocket and Socket for Serializable object
8.String based communication between Socket
9.Get email with Socket
10.Create PrintWriter from BufferedWriter, OutputStreamWriter and Socket
11.Read from server
12.Use Socket to read and write stream
13.Connects to a server at a specified host and port. It reads text from the console and sends it to the server
14.A simple network client that establishes a network connection to a specified port on a specified host, send an optional message across the connection
15.Reading Text from a Socket
16.Writing Text to a Socket
17.Sending a POST Request Using a Socket
18.Get the Date from server
19.Transfer a file via Socket
20.Ping a server
21.Read and write through socket
22.Read float number from a Socket
23.Read Object from Socket
24.deleting messages from a POP3 mailbox based on message size and Subject line
25.A timeout feature on socket connections
26.Write Objects From Socket
27.Write Double Using Sockets
28.Download WWW Page
29.Redirects incoming TCP connections to other hosts/ports
30.Socket Fetcher
31.Zip socket
32.This program shows how to interrupt a socket channel.
33.This program shows how to use sockets to send plain text mail messages.
34.Makes a socket connection to the atomic clock in Boulder, Colorado, and prints the time that the server sends.