C语言 套接字编程权限被拒绝
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20396820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Socket programing Permission denied
提问by user1345414
Following code is TCP server program just send back “HELLO!!” to client.
下面的代码是 TCP 服务器程序只发回“HELLO!!” 给客户。
When I run server with port 80, bind() is returned Permission denied.
当我使用端口 80 运行服务器时,返回 bind() Permission denied。
Port 12345 is OK.
端口 12345 正常。
How can I use port 80 for this server program?
我如何为这个服务器程序使用端口 80?
#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;
}
回答by Linus Kleen
Ports below 1024 are considered "privileged" and can only be bound to with an equally privileged user (read: root).
低于 1024 的端口被视为“特权”,并且只能与具有同等特权的用户(阅读:root)绑定。
Anything above and including 1024 is "free to use" by anyone.
任何人都可以“免费使用”以上任何内容(包括 1024)。
OT: you may know this already, but the port in your example is that for HTTP web servers. Anything listening to this port shouldspeak HTTP, too. A simple "hello world" does not suffice. ;-)
OT:您可能已经知道这一点,但是您示例中的端口是用于 HTTP Web 服务器的端口。任何监听这个端口的东西也应该说 HTTP。一个简单的“hello world”是不够的。;-)
回答by alexclooze
Only the root user is allowed to bind to ports <= 1024. Every ports > 1024 can be bound to by normal users.
只允许root用户绑定端口<= 1024。每个端口> 1024都可以被普通用户绑定。
Try executing your program as root or with sudo.
尝试以 root 身份或使用sudo.
回答by MOHAMED
you have to run your application with super user account (root)
您必须使用超级用户帐户(root)运行您的应用程序
Run your application with sudocommand
使用sudo命令运行您的应用程序

