Socket Programming Permission Denied

The following code is a TCP server program that simply sends back "HELLO !!" to the customer.

When I start the server with port 80, bind () returns Permission denied .

Port 12345 is fine.

How can I use port 80 for this server program?

 #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> int main(){ int sock0; struct sockaddr_in addr; struct sockaddr_in client; int len; int sock; char *message; message = "HELLO !!"; sock0 = socket(AF_INET,SOCK_STREAM,0); addr.sin_family = AF_INET; addr.sin_port = htons(80); inet_pton(AF_INET,"127.0.0.1",&addr,sizeof(addr)); bind(sock0,(struct sockaddr *)&addr,sizeof(addr)); perror("bind"); len = sizeof(client); sock = accept(sock0,(struct sockaddr *)&client,&len); perror("accept"); write(sock,message,sizeof(message)); perror("write"); close(sock); return 0; } 
+7
c sockets
source share
3 answers

Ports below 1024 are considered “privileged” and can only be associated with an equally privileged user (read: root ).

Everything above and including 1024 is “freely used” by anyone.

OT: you may already know this, but the port in your example is for HTTP web servers. Everything that listens on this port must also speak HTTP. A simple "hello world" is not enough .; -)

+15
source share

Only the root user is allowed to bind to ports <= 1024. Each port> 1024 can bind to regular users.

Try running your program as root or using sudo .

+7
source share

you need to run the application with the superuser account (root)

Launch the application using the sudo

+3
source share

All Articles