I am trying to understand how bind() works. I open a socket, and bind it to port 5001, but I don't execute listen() on it:

sockfd = socket(AF_INET, SOCK_STREAM, 0);

/* Initialize socket structure */
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 5001;

serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);

/* Now bind the host address using bind() call.*/
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
   perror("ERROR on binding");

printf("bound to 5001");

Then, the port is "in use":

$ nc -l 5001
nc: Address already in use

but when I try: netstat -ntpl, lsof -i :5001, sudo netstat -antp | grep 5001 none of them shows the 5001 port.

Is there a way to see which ports are bound, and the processes that owns them? Or, having the socket descriptor, show the port/ip/info of the socket

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.