开发者

Why is root required for listening on the loopback in Java?

开发者 https://www.devze.com 2023-04-10 15:40 出处:网络
How come when I try listening to a loopback host in Java (using a plain old socket), it requires root access, yet if I use nio, it doesn\'t? If I tried listening on any other language on the loopback,

How come when I try listening to a loopback host in Java (using a plain old socket), it requires root access, yet if I use nio, it doesn't? If I tried listening on any other language on the loopback, it doesn't require any elevated privileges too.

This is my code right now:

import jav开发者_开发问答a.net.*;

class Test
{
    public static void main( String[] args )
        throws Exception
    {
        ServerSocket server = new ServerSocket( 80 );
        while( true )
        {
            Socket socket = server.accept();
            System.out.print( "." );
        }
    }
}

When I run this as a normal user, this exception is thrown: Exception in thread "main" java.net.BindException: Permission denied. Yet when I run this as root, it works fine as expected.


You need root permissions to bind a socket in the port range 0-1023. These ports are used for common services like HTTP and SSH and it would be dangerous to allow random users to bind their arbitrary applications to these ports.

See wikipedia: http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports

Edit: Keep in mind that arbitrary applications can connect to well-known ports, just not bind to them. Otherwise users would not be able to run honest programs ssh or mozilla. This is likely why you are not able to reproduce this error in other languages.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号