检测服务器端口是否被占用
1 for (int port=begin; port <= end; port++){ 2 /*定义socket*/ 3 int server_sockfd = socket(AF_INET, SOCK_STREAM, 0); 4 5 /*定义sockaddr_in 的变量*/ 6 struct sockaddr_in server_sockaddr; 7 server_sockaddr.sin_family = AF_INET; 8 server_sockaddr.sin_addr.s_addr=htonl(INADDR_ANY); 9 server_sockaddr.sin_port = htons(port); 10 //server_sockaddr.sin_port = 0; /*端口范围是0~65535 1~1023为保留端口号*/ 11 12 /*检查端口占用情况,列出占用端口号*/ 13 if (bind (server_sockfd, (struct sockaddr *) &server_sockaddr, sizeof(\ 14 server_sockaddr)) == -1){ 15 printf ("%d\n", port); 16 alread_port_cnt++; 17 //break; 18 } else { 20 idle_port_cnt++; 21 } 22 close (server_sockfd); 23 }/*循环结束*/
用bind()函数就可以,成功返回0, 占用返回-1.
种树最好的时间是十年前,其次是现在。