问题
I'm trying following progam:
- If i use SUDO java to run everthing is fine, but I don't want to use SUDO
- 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
jetty-setuid.xm
l -- Put user-name is non-root userstart.ini
-- Change to EXEC and passingetc/jetty-setuid.xml
as first parameterjetty.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