accept函數(shù)是一個(gè)套接字函數(shù),用于接受客戶端的連接請求。它的使用方式如下:
#include <sys/types.h>
#include <sys/socket.h>
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
參數(shù)說明:
sockfd:服務(wù)端套接字描述符,即被監(jiān)聽的套接字;
addr:指向一個(gè)sockaddr結(jié)構(gòu)體的指針,用于存儲客戶端的地址信息;
addrlen:指向socklen_t類型的指針,用于存儲addr的長度;
返回值:
若成功,則返回一個(gè)新的套接字描述符,該套接字與客戶端建立連接;
若出錯(cuò),則返回-1,并設(shè)置errno。
使用accept函數(shù)的一般步驟如下:
創(chuàng)建一個(gè)套接字:使用socket函數(shù);
綁定地址:使用bind函數(shù);
監(jiān)聽連接請求:使用listen函數(shù);
接受連接請求:使用accept函數(shù);
使用接受到的套接字進(jìn)行通信;
關(guān)閉套接字:使用close函數(shù)。
以下是一個(gè)簡單的示例代碼:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int main() {
int sockfd, newsockfd, portno, clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
// 創(chuàng)建套接字
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
exit(1);
}
// 綁定地址
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 12345;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
perror("ERROR on binding");
exit(1);
}
// 監(jiān)聽連接請求
listen(sockfd, 5);
clilen = sizeof(cli_addr);
// 接受連接請求
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) {
perror("ERROR on accept");
exit(1);
}
// 使用接受到的套接字進(jìn)行通信
bzero(buffer, 256);
n = read(newsockfd, buffer, 255);
if (n < 0) {
perror("ERROR reading from socket");
exit(1);
}
printf("Message from client: %s\n", buffer);
// 關(guān)閉套接字
close(newsockfd);
close(sockfd);
return 0;
}
以上示例中,服務(wù)器創(chuàng)建了一個(gè)套接字,并綁定了地址。然后通過調(diào)用accept函數(shù)接受連接請求,并使用接受到的套接字進(jìn)行通信。最后關(guān)閉了套接字。