socket-programming:bind
تفاوتها
تفاوت دو نسخهٔ متفاوت از صفحه را مشاهده میکنید.
| socket-programming:bind [2024/06/18 00:28] – ایجاد شد pejman | socket-programming:bind [2024/06/18 01:00] (فعلی) – حذف شد pejman | ||
|---|---|---|---|
| خط 1: | خط 1: | ||
| - | ====== تابع ()bind ====== | ||
| - | |||
| - | در هر server پس از گرفتن file descriptor از طریق [[socket]] باید آن را به یک port متصل کنیم تا برای [[listen]] آماده باشد. این کار توسط [[bind]] انجام میشود. | ||
| - | <code C> | ||
| - | #include < | ||
| - | #include < | ||
| - | |||
| - | int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); | ||
| - | </ | ||
| - | |||
| - | |||
| - | تمام ورودی های [[bind]] از طریق [[getaddrinfo]] و [[socket]] آماده میشود. sockfd همان file descriptor حاصل از [[socket]] است و addr هم همان rp-> | ||
| - | |||
| - | |||
| - | مثال برای گرفتن file descriptor توسط [[socket]] و اتصال به یک port از طریق [[bind]] ، با کنترل تک تک استراکچرهای linked-list آماده شده توسط [[getaddrinfo]] : | ||
| - | |||
| - | <code C> | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | |||
| - | #define handle_error(msg) \ | ||
| - | do { perror(msg); | ||
| - | |||
| - | #define PORT " | ||
| - | |||
| - | int main() | ||
| - | { | ||
| - | int status; | ||
| - | struct addrinfo hints, *res, *rp; | ||
| - | int sockfd; | ||
| - | char *ipver, ipstr[INET6_ADDRSTRLEN]; | ||
| - | void *addr; | ||
| - | |||
| - | memset(& | ||
| - | hints.ai_family = AF_UNSPEC; | ||
| - | hints.ai_socktype = SOCK_DGRAM; | ||
| - | hints.ai_flags = AI_PASSIVE; | ||
| - | |||
| - | status = getaddrinfo(NULL, | ||
| - | if (status != 0) { | ||
| - | fprintf(stderr, | ||
| - | exit(EXIT_FAILURE); | ||
| - | } | ||
| - | |||
| - | for (rp = res; rp != NULL; rp = rp-> | ||
| - | sockfd = socket(rp-> | ||
| - | if (sockfd == -1) { | ||
| - | handle_error(" | ||
| - | continue; | ||
| - | } | ||
| - | status = bind(sockfd, | ||
| - | if (status == 0) | ||
| - | break; | ||
| - | handle_error(" | ||
| - | close(sockfd); | ||
| - | } | ||
| - | |||
| - | if (rp == NULL) { | ||
| - | fprintf(stderr, | ||
| - | exit(EXIT_FAILURE); | ||
| - | } | ||
| - | |||
| - | if (rp-> | ||
| - | ipver = " | ||
| - | addr = & | ||
| - | } else { | ||
| - | ipver = " | ||
| - | addr = & | ||
| - | } | ||
| - | |||
| - | inet_ntop(rp-> | ||
| - | fprintf(stdout, | ||
| - | |||
| - | close(sockfd); | ||
| - | freeaddrinfo(res); | ||
| - | |||
| - | return 0; | ||
| - | } | ||
| - | </ | ||
| - | |||
| - | خروجی | ||
| - | |||
| - | I got an IPv4 socket for 0.0.0.0 and bind to 3440 = 3 | ||
socket-programming/bind.1718657915.txt.gz · آخرین ویرایش: 2024/06/18 00:28 توسط pejman
