Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

listen() without calling bind()

I tried the following:

int sockfd = socket(...);
listen(sockfd, 10);
accept(sockfd, ...);

None of the calls failed, and the program just started blocking as if I had called bind(). What will happen in this case? Will it just be impossible to ever receive a connection, since it has no local address or port? Or was it implicitly assigned a local address and port, and now it is listening on those? If so, how can I retrieve what those are?

like image 468
Claudiu Avatar asked Apr 12 '09 00:04

Claudiu


1 Answers

The calls are working, but since you didn't bind the socket explicitly, the operating system or system library implicitly assigned a port and default binding for you (exactly the same as when you call connect(2) without calling bind(2) first). Also, since you asked about the TCP stuff earlier, I'm assuming you're talking about Internet sockets here.

Finding out what name the OS bound the socket to varies between operating systems, so you will have to look for your specific OS, but most operating systems provide a netstat or similar tool that you can use to query which applications are listening on which ports.,

As John mentions in a comment, you can use getsockname(2) to find a bound socket's name. Here is a short example:

// ...

// Create socket and set it to listen (we ignore error handling for brevity)
int sock = socket(AF_INET, SOCK_STREAM, 0);
listen(sock, 10);

// Sometime later we want to know what port and IP our socket is listening on
socklen_t addr_size = sizeof(struct sockaddr_in);
struck sockaddr_in addr;
getsockname(sock, (struct sockaddr *)&addr, &addr_size);

addr will now contain the IP address and port that your socket is listening on.

like image 133
Jason Coco Avatar answered Oct 12 '22 14:10

Jason Coco