Using Java Program How to programmatically start Jetty on port 80 as non-root user

帅比萌擦擦* 提交于 2019-12-10 21:27:07

问题


I'm trying following progam:

  1. If i use SUDO java to run everthing is fine, but I don't want to use SUDO
  2. without SUDO i get following error: SocketException: Permission Denied (as its PORT 80)

Using jetty documentation, I get this to work using command line where i change

  1. jetty-setuid.xml -- Put user-name is non-root user
  2. start.ini -- Change to EXEC and passing etc/jetty-setuid.xml as first parameter
  3. jetty.xml -- To have port number as 80

then I still do sudo as non-root user -- like -> sudo java -jar start.jar Jetty starts on port 80 as non-root user.

I want to ACHIEVE the same using JAVA Program. Any help/comments are appreciated.

package my.package;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.nio.SelectChannelConnector;

public class JettyTest {


public static void main(String[] args) throws Exception
{
    Server server = new Server();
    System.out.println("Created new server, now going to start");
    SelectChannelConnector connector0 = new SelectChannelConnector();
    connector0.setPort(80); //on port 80
    connector0.setMaxIdleTime(30000);
    connector0.setRequestHeaderSize(8192);

    server.setConnectors(new Connector[]{ connector0 });

    server.setHandler(new MyHandler()); //simple hello world handler

    server.start();
    System.out.println("started server on port 80");
    server.join();
}

}

回答1:


You must use sudo somehow on Unix to elevate to root priviledges. Otherwise you cannot get port 80.

For Java programs, the sudo must be applied to the java command itself, but it is generally a bad idea to do that.

A more conservative solution is to bind to another port, say 8080, and then reroute port 80 to that port. The commands to do so varies wildly between operating systems and may not even exist on some older Unix-versions.




回答2:


Sudo elevates the privileges of your command to root level. The reason why you need to "sudo" here (or, more generally speaking, run the command as root) is the fact that in Linux the ports below 1024 are reserved to root.

In other words - you cannot run jetty (or any other service) on port 80 if you're not root.

The simplest solution here is to run Jetty on another port (8080 is a common one).

If you still want users to access the service on the default port, consult http://wiki.eclipse.org/Jetty/Howto/Port80 and http://docs.codehaus.org/display/JETTY/port80 .



来源:https://stackoverflow.com/questions/13257880/using-java-program-how-to-programmatically-start-jetty-on-port-80-as-non-root-us

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!