Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.net.BindException: Permission denied when creating a ServerSocket on Mac OSX

I Tried to run a Java socket in mac with eclipse but it doesn't work. I got this error:

Exception in thread "main" java.net.BindException: Permission denied

    at java.net.PlainSocketImpl.socketBind(Native Method)
    at java.net.PlainSocketImpl.socketBind(PlainSocketImpl.java:521)
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:414)
    at java.net.ServerSocket.bind(ServerSocket.java:326)
    at java.net.ServerSocket.<init>(ServerSocket.java:192)
    at java.net.ServerSocket.<init>(ServerSocket.java:104)
    at server.MessageServer.main(MessageServer.java:11)

How can i make it to run?

package server; //ChatServer 
import java.io.*; 
import java.net.*; 

public class MessageServer { 

public static void main (String args[]) throws IOException { 
    int port = 100; 
    ServerSocket server = new ServerSocket (port); 
    System.out.println("Server is started!"); 

    while (true) { 
        Socket client = server.accept (); 
        System.out.println ("Accepted from " + client.getInetAddress ()); 
        MessageHandler handler = new MessageHandler (client); 
        handler.start(); 
        } 
    } 
}
like image 613
Kevbear Avatar asked Aug 28 '14 09:08

Kevbear


4 Answers

You can't open a port below 1024, if you don't have root privileges and from the code you posted in your comment, you seem to be trying to open port 100 which confirms my theory.

You need to use a port which is higher than 1024, if you're running the code under a non-root user.

like image 135
carlspring Avatar answered Oct 18 '22 02:10

carlspring


Unix-based systems declare ports < 1024 as "privileged" and you need admin rights to start a server.

For testing, use a port number >= 1024.

When deploying the server in production, run it with admin rights.

like image 30
Aaron Digulla Avatar answered Oct 18 '22 02:10

Aaron Digulla


I had the same issue and my port numbers were below 1024 changing port number to above 1024 solved my problem. Ports below 1024 are called Privileged Ports and in Linux (and most UNIX flavors and UNIX-like systems), they are not allowed to be opened by any non-root user.

like image 4
confused Avatar answered Oct 18 '22 04:10

confused


Many systems declare ports that are less than 1024 as "admin rights" ports. Meaning, if you're only using this for basic testing use a higher port such as 2000. This will clear the exception that you're getting by running your current program.

    int port = 100; 
    ServerSocket server = new ServerSocket (port); 

Change that to something such as:

    int port = 2000; 
    ServerSocket server = new ServerSocket (port); 
like image 1
Cats4Life Avatar answered Oct 18 '22 02:10

Cats4Life