Prak
Prak

Reputation: 1069

Bind and socket programming

Is it necessary to bind a socketfd to a IP addrees while writting a server socket programming. I mean is it possble to write a socket programming without calling bind system call? Like socket -> listen -> accept -> read/write/ -> close.

Upvotes: 0

Views: 300

Answers (2)

Ed Heal
Ed Heal

Reputation: 59987

You use bind at the server end.

Simply imagine it is a switch board for your office. The bind gives it a phone number so that other people know what number to phone. The the operator listen answers and puts the call through (i.e. process it).

Upvotes: 1

mattn
mattn

Reputation: 7723

socket should be bind to port or unix socket file. Do you mean you don't want to define port number for listen? Then bind port number 0. It works with random port.

memset((char *) &reader_addr, 0, sizeof(reader_addr));
reader_addr.sin_family = PF_INET;
reader_addr.sin_addr.s_addr = htonl(INADDR_ANY);
reader_addr.sin_port = 0;

if (bind(server_fd, (struct sockaddr *)&reader_addr, sizeof(reader_addr)) < 0) {
    perror("reader: bind");
    exit(1);
}

Upvotes: 2

Related Questions