Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

c - Socket programing Permission denied

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. ;-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...