[英]C bind to a specified TCP port
i have created a Linux network app with C and it kind of works 我用C创建了一个Linux网络应用程序,它有点工作
except that it every time i run it , it binds to a new Random port 除了它每次运行它,它绑定到一个新的随机端口
//Create Socket
int socket_desc;
socket_desc=socket(AF_INET,SOCK_STREAM,0);
if (socket_desc==-1)
perror("Create socket");
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
//Port defined Here:
address.sin_port=htons(81);
//Bind
bind(socket_desc,(struct sockaddr *)&address,sizeof(address));
listen(socket_desc,32);
//Do other stuff (includes accepting connections)
as you can see i have specified port but it still chooses a free Random port 正如你所看到我指定了端口,但它仍然选择一个免费的随机端口
any help or link to a good tutorial on this is appreciated 任何帮助或链接到这方面的良好教程表示赞赏
您需要使用大于1024的端口号。小于1024的端口号是保留端口,由标准服务使用。
There are two reasons of this behaviour (when you specify port, but system binds socket to a random one): 这种行为有两个原因(当您指定端口时,但系统将套接字绑定到随机的):
- If you ask for port below 1024. This is certainly your case 如果你要求1024以下的端口。这肯定是你的情况
- If you forgot to use
htons()
function. 如果忘了使用htons()
函数。 In this case bytes of port number are used in wrong order and that leads to #1. 在这种情况下,端口号的字节使用顺序错误,导致#1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.