You can use bind() to detect if a port is in use or not and you can also
use port 0 and bind will use the next available high port.
Code:
struct sockaddr_in sin;
int socket, port = 22;
socket = socket(AF_INET, SOCK_STREAM, 0));
if(socket == -1)
return -1;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = 0;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_family = AF_INET;
if (bind(socket, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)) == -1) {
if (errno == EADDRINUSE)
printf("Port in use");
return -1;
}
If port 0 was used and bind selects next free port then use following code to
get socket info and the port that is used.
Code:
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) != -1)
printf("port number %d\n", ntohs(sin.sin_port));
Regards,
Henrik Andersson