Solved

Can I open any TCP/UDP ports when using an Applet?

Posted on 2001-07-01
9
2,188 Views
Last Modified: 2013-11-23
Hi,

I want to use JAVA applet for communication between Client/Server. The client has to listen to port 162 and connect (send messages) to the server port no. 161. The connection is over UDP.
I am aware to JAVA applets' restrictions, the client applet is planned to perform the connection only to/from the host, which it was download from. My question is: can I connect to any port on this host (the server) and listen to any port on my local host (the client)?

Code example or any other example will be usefull too.
Thanks,
Amir.
gooliver@yahoo.com
0
Comment
Question by:AmirG
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 6

Expert Comment

by:jpk041897
ID: 6242560
Yes, you can open any port for UDP provided there are no firewalls involved.

If firewalls are involved you would be prety much forced to either open the UDP port on the firewall or tunnel your packets over TCP port 80.

As far as a UDP server (with no firewall) is involved, your code would look like this:

import java.net.*;
import java.io.*;

// START main1
class EchoServer extends Thread {
    private DatagramSocket sock = null;
    EchoServer(int port) {
      try {
          sock = new DatagramSocket(port);
      } catch (SocketException e) {
          e.printStackTrace();
      }
    }
    public void run() {
      if (sock == null)
          return;

      byte[] inbuf = new byte[1024];
      DatagramPacket request = new DatagramPacket(inbuf, inbuf.length);
      try {
          while (true) {
            sock.receive(request);
            sock.send(request); // just return what was sent
          }
      } catch (IOException e) {
          e.printStackTrace();
      }
    }
}
// END main1

class Main {
    static int echo_port = 1257;

// START main2
public static void echo(String msg, InetAddress dst, int port) {
    byte[] inbuf = new byte[1024];  // default size
    byte[] outbuf = msg.getBytes();

    try {
      DatagramSocket client = new DatagramSocket(); // any port
      DatagramPacket request = new DatagramPacket(outbuf, outbuf.length,
          dst, port);
      DatagramPacket reply = new DatagramPacket(inbuf, inbuf.length);
      client.send(request);
      client.receive(reply);
      client.close();
      System.out.println(new String(reply.getData()));
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
}
// END main2

    public static void main(String[] args) {
      if (args.length != 1) {
          System.err.println("Usage: java Main <message>");
          System.exit(1);
      }

      // start server
      EchoServer srv = new EchoServer(echo_port);
      srv.setDaemon(true);
      srv.start();

      try {
          String msg = "\n";
          InetAddress dst = InetAddress.getLocalHost();

          echo(args[0], dst, echo_port);

      } catch (UnknownHostException e) {
          System.err.println("Host not found: " + e);
      }

// START local
try {
    DatagramSocket client = new DatagramSocket();
    System.out.println("Using port number " + client.getLocalPort());
    System.out.println("Using address " + client.getLocalAddress());
// UNCOM      ...
    client.close();
} catch (SocketException e) {
    e.printStackTrace();
}
// END local
    }
}


The client would look like:

import java.net.*;
import java.io.*;

class Main {
    public static String dgExchange(String msg, InetAddress dst, int port) {
        byte[] outbuf = msg.getBytes();
        byte[] inbuf = new byte[256];  // default size

        try {
            // Send datagram
            DatagramPacket request =
                new DatagramPacket(outbuf, outbuf.length, dst, port);
            DatagramSocket sock = new DatagramSocket();
            sock.send(request);

            // Wait for reply
            DatagramPacket reply = new DatagramPacket(inbuf, inbuf.length);
            sock.receive(reply);

            System.out.println(
                "Received packet from:" + reply.getAddress() +
                " port: " + reply.getPort() +
                " length: " + reply.getLength());

            sock.close();
            return (new String(reply.getData()));
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (null);
    }

    public static void main(String[] args) {
        try {
            String msg = "\n";
            int port = 13;
            InetAddress dst = InetAddress.getLocalHost();

            if (args.length > 0) {
                port = Integer.parseInt(args[0]);
                if (args.length >= 2)
                    msg = args[1];
                if (args.length == 3)
                    dst = InetAddress.getByName(args[2]);
            }

            System.out.println(dgExchange(msg, dst, port));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}


Hope this helps.
0
 

Author Comment

by:AmirG
ID: 6244250
Please ignore the firewall problem, is it possible to open port no. 162 on my local machine (the applet side) for listening and sending messages to port 161 on the server side?
0
 

Author Comment

by:AmirG
ID: 6244753
Please ignore the firewall problem, is it possible to open port no. 162 on my local machine (the applet side) for listening and sending messages to port 161 on the server side?
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 6

Accepted Solution

by:
jpk041897 earned 200 total points
ID: 6246099
Yes, though for an applet, certain security restrictions apply.

The browsers security sandbox by default, as of JDK 1.2, will only allow opening port 80.

On JDK 1.1 you only need to pack your applet in a JAR file and sign it. On JDK 1.2 and above you also need to add a security policy file to the JAR file in order to be allowed to open port 161.

The server might or might not allow the opening of the port depending on architecture. For example, on a moderatly secure UNIX system you would have to modify some network configuration files to open the port at the OS level and on JDK 1.3 you would also need to create a Java security manifest.
0
 
LVL 3

Expert Comment

by:stimpyjcat
ID: 6248745
On a Unix machine, ports below 1024 require superuser (root) access.

0
 

Author Comment

by:AmirG
ID: 6252974
And if I control also the server OS (I use Apache web-sever on RTOS), is it possible to open standard ports below 1024?  
0
 
LVL 3

Expert Comment

by:stimpyjcat
ID: 6253273
It likely depends on the configuration of RTOS, but usually embedded OSes don't default to a lot of restrictions.  You should just make sure there isn't already a process using the port to which you wish to bind.

netstat ("netstat -a") is a common tool that will show you which ports are in use.

Port 161/162 is not a good choice, since it is used by SNMP, and is likely to be either in use already or interpreted as SNMP instead of *your* messages on the other end.

Unless you are actually trying to implement some form of snmp.
0
 
LVL 3

Expert Comment

by:stimpyjcat
ID: 6253920
BTW, jpk explained the other restrictions you'll run into when attempting to use a listening socket where the applet is downloaded (client).

0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 8950564


No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:


--  points to jpk


Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
sudhakar_koundinya
EE Cleanup Volunteer
---------------------
If you feel that your question was not properly addressed, or that none of the comments received were appropriate answers, please post your concern in THIS thread.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Protect jar file - windows app 2 65
session migration servlets 2 42
MySQL  on Tomcat 8 71
Fast way to search item into Java Array (Rhino compatible) 2 31
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question