Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket programing Permission denied

Tags:

c

sockets

Following code is TCP server program just send back “HELLO!!” to client.

When I run server with port 80, bind() is returned Permission denied.

Port 12345 is OK.

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;
}
like image 948
user1345414 Avatar asked Dec 05 '13 09:12

user1345414


3 Answers

Ports below 1024 are considered "privileged" and can only be bound to with an equally privileged user (read: root).

Anything above and including 1024 is "free to use" by anyone.

OT: you may know this already, but the port in your example is that for HTTP web servers. Anything listening to this port should speak HTTP, too. A simple "hello world" does not suffice. ;-)

like image 64
Linus Kleen Avatar answered Nov 04 '22 03:11

Linus Kleen


Only the root user is allowed to bind to ports <= 1024. Every ports > 1024 can be bound to by normal users.

Try executing your program as root or with sudo.

like image 21
akluth Avatar answered Nov 04 '22 03:11

akluth


you have to run your application with super user account (root)

Run your application with sudo command

like image 6
MOHAMED Avatar answered Nov 04 '22 01:11

MOHAMED