[OPENSSL笔记] I/O抽象
![]() |
BIO常用API概览 |
Memory sources/sinks
![]() |
Memory BIO |
示例:
/* Create a read/write BIO */
bio = BIO_new(BIO_s_mem());
/* Create a read-only BIO using an allocated buffer */
buffer = malloc(4096);
bio = BIO_new_mem_buf(buffer, 4096);
/* Create a read-only BIO using a C-style string */
bio = BIO_new_mem_buf("This is a read-only buffer", -1);
/* Get a pointer to a memory BIO's memory segment */
BIO_get_mem_ptr(bio, &buffer);
/* Prevent a memory BIO from destorying its memory segent when it is destoryed*/
BIO_set_close(bio, BIO_NOCLOSE);
File BIO
![]() |
示例:
/* Create a buffered file BIO with an existing FILE object that will be closed when the BIO is destoryed */
file = fopen();
bio = BIO_new(BIO_s_file());
BIO_set_file(bio, file, BIO_CLOSE);
/* Create an unbuffered file BIO with an existing file descriptor that will not be closed when the BIO destoryed. */
fd = open("filename.ext", O_RDWR);
bio = BIO_new(BIO_s_fd());
BIO_set_fd(bio, fd, BIO_NOCLOSE);
/* Create a buffered file BIO with a new FILE object owned by the BIO */
bio = BIO_new_file("filename.ext", "w");
/* Create an unbuffered file BIO with an existing file descriptor that will be closed when the BIO is destoryed */
fd = open("filename.ext", O_RDWR);
bio = BIO_new_fd(fd, BIO_CLOSE);
socket BIO
![]() |
soceket accpet补充:
当一个新连接建立后,一个新的BIO对象被创建,并被链在原来的accpet BIO上,需把新BIO对象移除链才可以使用。而accpet connection可以继续用于accept其他的连接。
例:
/*
Create a socket BIO attached to an already existing socket descriptor.
The socket descriptor will not be closed when the BIO is destroyed
*/
bio = BIO_new(BIO_s_socket);
BIO_set_fd(bio, sd, BIO_NOCLOSE);
/*
Create a socket BIO attached to an already existing socket descriptor.
The socket descriptor will be closed when the BIO is destoryed.
*/
bio = BIO_new_socket(sd, BIO_CLOSE);
/* Create a socket BIO to establish a connection to a remote host. */
bio = BIO_new(BIO_s_connect());
BIO_set_conn_hostname(bio, "www.ora.com");
BIO_set_conn_port(bio, "http");
BIO_do_connect(bio);
/* Create a socket BIO to listen for an incoming connection. */
bio = BIO_new(BIO_s_accept());
BIO_set_accpet_port(bio, "https");
BIO_do_accept(bio); /* place the underlying socket into listening mode */
for(;;)
{
BIO_do_accept(bio); /* wait for a new connection*/
new_bio = BIO_pop(bio);
/* new_bio now behaves like a BIO_s_socket() BIO */
}