Question

I'm supposed to make a communicator in C, based on dgrams. I don't know what arguments should I pass to bind() function. I skimmed through most UDP-chat questions & codes here on StackOverflow but I still can't find any specific information on the issue.

What type of address structure should I use?

What port can I use? Any number bigger than 1024 ?

What IP adress do I bind my socket with? (most of people put INADDR_ANY but isn't it for receiving only?)

Also, do I need multiple sockets? One for receiving & another for sending messages.

Was it helpful?

Solution

What type of address structure should I use?

If you are using IPv4, use a sockaddr_in. If you want to use IPv6 instead, use a sockaddr_in6.

What port can I use? Any number bigger than 1024 ?

Yes, assuming no other program is already using that port number for its own UDP socket. (If another program is using the port number you chose, it will cause bind() to fail with errno EADDRINUSE)

What IP adress do I bind my socket with? (most of people put INADDR_ANY but isn't it for receiving only?)

INADDR_ANY is what you generally want to use. It tells the OS that you want to receive incoming UDP packets on any of the computers network interfaces. (If you only wanted to receive UDP packets from a particular network interface, OTOH, e.g. only on WiFi, you could specify that network interface's IP address instead)

Also, do I need multiple sockets? One for receiving & another for sending messages.

You can have multiple sockets if you want, but it's not necessary to do it that way. You can instead use a single socket for both sending and receiving UDP packets. One common pattern is to use a single socket, set to non-blocking mode, and something like select() or poll() to multiplex the input and output needs of your program. An alternative pattern would be to use two threads (one for sending and one for receiving), blocking I/O, and either one or two sockets (depending on whether you prefer to have the two threads share a socket, or give each thread its own socket). I prefer the single-threaded/single-socket/select() solution myself, as I think it is the least error-prone approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top