简体   繁体   中英

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.

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);
}

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 (ie process it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM