嗨,我想知道是否有更简单的方法来检查端口号是否可用,我想保留它以便我可以提前使用它?下面的代码就是这样做的,但它似乎过于复杂。
int getSocketNo(){
socklen_t namelen;
struct sockaddr_in node;
int sock_1;
/* ----Address information for use with bind---- */
node.sin_family = AF_INET; /* it is an IP address */
node.sin_port = 0;
node.sin_addr.s_addr = INADDR_ANY; /* use any interface on this host*/
/* ----Create TCP/IP socket---- */
sock_1 = socket(AF_INET, SOCK_STREAM, 0);
if (sock_1 == -1) {
perror("socket() Socket was not created");
exit(-1);
}
while(1){
/* ----Bind socket to address and port---- */
if (bind(sock_1, (struct sockaddr *) &node, sizeof(node))) {
perror("Server bind error");
continue;
}
int y = 1; // not sure what this does yet
setsockopt(sock_1, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(y));
/* ----Find out what port number was assigned---- */
namelen = sizeof(node);
if (getsockname(sock_1, (struct sockaddr *) &node, &namelen)) {
perror("Server get port number");
exit(-1);
}
close(sock_1);
break;
}
return ntohs(node.sin_port);
}