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\n",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 地址和端口標識了接入互聯網主機的唯一 一個進程。
---------------------

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM