34 socklen_t addrSize =
sizeof(
struct sockaddr_storage);
38 static bool Xcp_EnableSocketOption(
int sock,
int option);
39 static bool Xcp_DisableSocketOption(
int sock,
int option);
41 static bool Xcp_EnableSocketOption(
int sock,
int option) {
42 #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L 43 const char enable = 1;
45 if (setsockopt(sock, SOL_SOCKET, option, &enable,
sizeof(
int)) < 0) {
49 if (setsockopt(sock, SOL_SOCKET, option, &(
const char){1},
sizeof(int)) < 0) {
56 static bool Xcp_DisableSocketOption(
int sock,
int option) {
57 #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L 58 const char enable = 0;
60 if (setsockopt(sock, SOL_SOCKET, option, &enable,
sizeof(
int)) < 0) {
64 if (setsockopt(sock, SOL_SOCKET, option, &(
const char){0},
sizeof(int)) < 0) {
71 void XcpTl_Init(
void) {
72 struct addrinfo hints;
73 struct addrinfo *addr_info = NULL;
80 memset(&hints, 0,
sizeof(hints));
81 XcpTl_Connection.socketType = Xcp_Options.tcp ? SOCK_STREAM : SOCK_DGRAM;
82 sprintf(port,
"%d", Xcp_Options.port);
83 hints.ai_family = Xcp_Options.ipv6 ? PF_INET6 : PF_INET;
84 hints.ai_socktype = XcpTl_Connection.socketType;
85 hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
86 ret = getaddrinfo(address, port, &hints, &addr_info);
89 XcpHw_ErrorMsg(
"XcpTl_Init::getaddrinfo()", errno);
93 sock = socket(addr_info->ai_family, addr_info->ai_socktype, addr_info->ai_protocol);
95 XcpHw_ErrorMsg(
"XcpTl_Init::socket()", errno);
98 if (bind(sock, addr_info->ai_addr, addr_info->ai_addrlen) == -1) {
99 XcpHw_ErrorMsg(
"XcpTl_Init::bind()", errno);
102 if (XcpTl_Connection.socketType == SOCK_STREAM) {
103 if (listen(sock, 1) == -1) {
104 XcpHw_ErrorMsg(
"XcpTl_Init::listen()", errno);
109 memcpy(&XcpTl_Connection.localAddress, &addr_info->ai_addr,
sizeof(XcpTl_Connection.localAddress));
111 XcpTl_Connection.boundSocket = sock;
112 freeaddrinfo(addr_info);
113 if (!Xcp_EnableSocketOption(XcpTl_Connection.boundSocket, SO_REUSEADDR)) {
114 XcpHw_ErrorMsg(
"XcpTl_Init:setsockopt(SO_REUSEADDR)", errno);
118 void XcpTl_DeInit(
void) { close(XcpTl_Connection.boundSocket); }
120 void XcpTl_Send(uint8_t
const *buf, uint16_t len) {
122 XCP_TL_ENTER_CRITICAL();
123 if (XcpTl_Connection.socketType == SOCK_DGRAM) {
124 if (sendto(XcpTl_Connection.boundSocket, (
char const *)buf, len, 0,
125 (
struct sockaddr
const *)&XcpTl_Connection.connectionAddress, addrSize) == -1) {
126 XcpHw_ErrorMsg(
"XcpTl_Send:sendto()", errno);
128 }
else if (XcpTl_Connection.socketType == SOCK_STREAM) {
129 if (send(XcpTl_Connection.connectedSocket, (
char const *)buf, len, 0) == -1) {
130 XcpHw_ErrorMsg(
"XcpTl_Send:send()", errno);
131 close(XcpTl_Connection.connectedSocket);
134 XCP_TL_LEAVE_CRITICAL();