下载 FreeRTOS
 

出色的 RTOS & 嵌入式软件

最新资讯
简化任何设备的身份验证云连接。
利用 CoAP 设计节能型云连接 IoT 解决方案。
11.0.0 版 FreeRTOS 内核简介:
FreeRTOS 路线图和代码贡献流程。
使用 FreeRTOS 实现 OPC-UA over TSN。

FreeRTOS_socket()

[FreeRTOS-Plus-TCP API 引用]

FreeRTOS_sockets.h
Socket_t FreeRTOS_socket( BaseType_t xDomain, BaseType_t xType, BaseType_t xProtocol );
		

创建 TCP 或 UDP 套接字

请参阅 FreeRTOS-Plus-TCP 联网教程 获取有关使用 TCP 和 UDP 套接字的更多信息。

参数:

xDomain   设置为 FREERTOS_AF_INET 以创建使用 IPv4 地址系列的套接字。
设置为 FREERTOS_AF_INET6 以创建使用 IPv6 地址系列的套接字。
其他值无效。

xType   设置为 FREERTOS_SOCK_STREAM 以创建 TCP 套接字。
设置为 FREERTOS_SOCK_DGRAM 以创建 UDP 套接字。
其他值无效。

xProtocol   设置为 FREERTOS_IPPROTO_TCP 以创建 TCP 套接字。
设置为 FREERTOS_IPPROTO_UDP 以创建 UDP 套接字。
其他值无效。

返回:

如果成功创建套接字,则返回套接字句柄。 如果 没有足够的 FreeRTOS 堆内存供待创建的套接字使用, 则返回 FREERTOS_INVALID_SOCKET。

用法示例:

以下代码片段分别展示了如何创建 UDP 和 TCP 套接字 。


/* FreeRTOS-Plus-TCP sockets include. */
#include "FreeRTOS_sockets.h"

void aFunction( void )
{
/* Variable to hold the created socket. */
Socket_t xSocket;
struct freertos_sockaddr xBindAddress;

/* Create a UDP socket. */
xSocket = FreeRTOS_socket( FREERTOS_AF_INET, /* For IPv4 socket */

/* use FREERTOS_AF_INET6 for IPv6 UDP socket */

FREERTOS_SOCK_DGRAM,
FREERTOS_IPPROTO_UDP );

/* Check the socket was created successfully. */
if( xSocket != FREERTOS_INVALID_SOCKET )
{
/* The socket was created successfully and can now be used to send data
using the FreeRTOS_sendto() API function. Sending to a socket that has
not first been bound will result in the socket being automatically bound
to a port number. Use FreeRTOS_bind() to bind the socket to a
specific port number. This example binds the socket to port 9999. The
port number is specified in network byte order, so FreeRTOS_htons() is
used. */

xBindAddress.sin_port = FreeRTOS_htons( 9999 );
if( FreeRTOS_bind( xSocket, &xBindAddress, sizeof( &xBindAddress ) ) == 0 )
{
/* The bind was successful. */
}
}
else
{
/* There was insufficient FreeRTOS heap memory available for the socket
to be created. */

}
}



使用 FreeRTOS_socket() API 函数创建 UDP 套接字的示例



/* FreeRTOS-Plus-TCP sockets include. */
#include "FreeRTOS_sockets.h"

void aFunction( void )
{
/* Variable to hold the created socket. */
Socket_t xSocket;
struct freertos_sockaddr xBindAddress;

/* Create a TCP socket. */
xSocket = FreeRTOS_socket( FREERTOS_AF_INET,
FREERTOS_SOCK_STREAM,
FREERTOS_IPPROTO_TCP );

/* Check the socket was created successfully. */
if( xSocket != FREERTOS_INVALID_SOCKET )
{
/* The socket was created successfully and can now be used to connect to
a remote socket using FreeRTOS_connect(), before sending data using
FreeRTOS_send(). Alternatively the socket can be bound to a port using
FreeRTOS_bind(), before listening for incoming connections using
FreeRTOS_listen(). */

}
else
{
/* There was insufficient FreeRTOS heap memory available for the socket
to be created. */

}
}



使用 FreeRTOS_socket() API 函数创建 TCP 套接字的示例
Copyright (C) Amazon Web Services, Inc. or its affiliates. All rights reserved.