socket-programming:connect
تفاوتها
تفاوت دو نسخهٔ متفاوت از صفحه را مشاهده میکنید.
| socket-programming:connect [2024/06/18 00:28] – ایجاد شد pejman | socket-programming:connect [2024/06/18 01:00] (فعلی) – حذف شد pejman | ||
|---|---|---|---|
| خط 1: | خط 1: | ||
| - | ====== تابع ()connect ====== | ||
| - | |||
| - | در client ، بعد از فراخوانی [[socket]] از [[connect]] برای ایجاد اتصال به server استفاده می کنیم. سیستم عامل اتوماتیک یک پورت بزرگتر از 1024 را به عنوان source port برای ارتباط با server اختصاص خواهد داد: | ||
| - | |||
| - | <code C> | ||
| - | // man 2 connect | ||
| - | #include < | ||
| - | #include < | ||
| - | |||
| - | int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen); | ||
| - | </ | ||
| - | |||
| - | مثال | ||
| - | |||
| - | <code C> | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | |||
| - | #define handle_error(msg) \ | ||
| - | do { perror(msg); | ||
| - | |||
| - | #define SERVER " | ||
| - | #define PORT " | ||
| - | |||
| - | int main() | ||
| - | { | ||
| - | int status, sockfd; | ||
| - | struct addrinfo hints, *res, *rp; | ||
| - | |||
| - | memset(& | ||
| - | hints.ai_family = AF_UNSPEC; | ||
| - | hints.ai_socktype = SOCK_STREAM; | ||
| - | hints.ai_protocol = 0; | ||
| - | |||
| - | status = getaddrinfo(SERVER, | ||
| - | 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 = connect(sockfd, | ||
| - | if (status == 0) | ||
| - | break; | ||
| - | |||
| - | handle_error(" | ||
| - | close(sockfd); | ||
| - | } | ||
| - | freeaddrinfo(res); | ||
| - | |||
| - | if (rp == NULL) { | ||
| - | fprintf(stdout, | ||
| - | } else { | ||
| - | fprintf(stdout, | ||
| - | close(sockfd); | ||
| - | } | ||
| - | |||
| - | return 0; | ||
| - | } | ||
| - | </ | ||
| - | خروجی | ||
| - | |||
| - | bind() error: Connection refused | ||
socket-programming/connect.1718657894.txt.gz · آخرین ویرایش: 2024/06/18 00:28 توسط pejman
