socket bind 随机端口

 https://www.cprogramming.com/code_blocks/

这个地址可以下载c, c++的编译器,在windows下可以用的 IDE.

bind到端口0上,系统就会自动分配,但是可能不是随机的,而是根据系统的算法。
也可以用rand算个随机数出来,然后bind,如果bind不成功就取下一个随机数。

 At this point, you can reach for the port 0 trick: on both Windows and Linux, if you bind a socket to port 0, the kernel will assign it a free port number somewhere above 1024.

原文:https://blog.csdn.net/Borntodieee/article/details/78939923 

https://cboard.cprogramming.com/linux-programming/89244-bind-chosing-port.html

I set the server.sin_port=0 and then I call the bind function that doesn't return any error:

Where can I get the port that was asigned by the bind function?

int sd;         //server descriptor
struct sockaddr_in server;
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_addr.s_addr=htonl(INADDR_ANY);
server.sin_port=htons(0);
 
if(bind(sd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1); // error
 
printf("%d
",ntohs(server.sin_port)); //is still 0

  怎么获取系统真正分配的随机端口呢?

All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler

Don't use bzero -- it's been obsolete for decades. It makes you look like a stupid hacker (I'm not saying you are one -- but let me guess, you've been learning socket programming by reading hacking sites, right?) Use memset() instead.

Also, why do you need to know the port number? Why are you binding without specifying the port, anyway?

------------------------------------------------------------------------------------------------------------------


TCP/IP 协议中的端口在报头中占2个字节即16位,范围是从0-65535。端口号用来表示和区别网络中的不同应用程序
端口分类
(1)公认端口(Well Known Ports):0-1023之间的端口号,也叫Well Known ports。这些端口由 IANA 分配管理。IANA 把这些端口分配给最重要的一些应用程序,让所有的用户都知道,当一种新的应用程序出现后,IANA必须为它指派一个公认端口。
常用的公认端口有:
FTP : 21
TELNET : 23
SMTP : 25
DNS : 53
TFTP : 69
HTTP : 80
SNMP : 161
(2)注册端口(Registered Ports):从1024-49151。是公司和其他用户向互联网名称与数字地址分配机构(ICANN)登记的端口号,利用因特网的传输控制协议(TCP)和用户数据报协议(UDP)进行通信的应用软件需要使用这些端口。在大多数情况下,这些应用软件和普通程序一样可以被非特权用户打开。
(3)客户端使用的端口号:49152~65535.这类端口号仅在客户进程运行时才动态选择,因此又叫做短暂端口号。被保留给客户端进程选择暂时使用的。也可以理解为,客户端启动的时候操作系统随机分配一个端口用来和服务器通信,客户端进程关闭下次打开时,又重新分配一个新的端口。
总结
端口就像一道门,外部可以通过不同的端口和本机上不同服务的进程进行交流。而IP 地址和端口标识了接入互联网主机的唯一 一个进程。
---------------------

原文地址:https://www.cnblogs.com/oxspirt/p/10118348.html