open62541 1.3.12
Open source implementation of OPC UA
Loading...
Searching...
No Matches
posix_sockets.h
Go to the documentation of this file.
1#if !defined(__POSIX_SOCKET_TEMPLATE_H__)
2#define __POSIX_SOCKET_TEMPLATE_H__
3
4#include <stdio.h>
5#include <sys/types.h>
6#if !defined(WIN32)
7#include <sys/socket.h>
8#include <netdb.h>
9#else
10#include <ws2tcpip.h>
11#endif
12#if defined(__VMS)
13#include <ioctl.h>
14#endif
15#include <fcntl.h>
16
17/*
18 A template for opening a non-blocking POSIX socket.
19*/
20int open_nb_socket(const char* addr, const char* port);
21
22int open_nb_socket(const char* addr, const char* port) {
23 struct addrinfo hints = {0};
24
25 hints.ai_family = AF_UNSPEC; /* IPv4 or IPv6 */
26 hints.ai_socktype = SOCK_STREAM; /* Must be TCP */
27 int sockfd = -1;
28 int rv;
29 struct addrinfo *p, *servinfo;
30
31 /* get address information */
32 rv = getaddrinfo(addr, port, &hints, &servinfo);
33 if(rv != 0) {
34 fprintf(stderr, "Failed to open socket (getaddrinfo): %s\n", gai_strerror(rv));
35 return -1;
36 }
37
38 /* open the first possible socket */
39 for(p = servinfo; p != NULL; p = p->ai_next) {
40 sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
41 if (sockfd == -1) continue;
42
43 /* connect to server */
44 rv = connect(sockfd, p->ai_addr, p->ai_addrlen);
45 if(rv == -1) {
46 close(sockfd);
47 sockfd = -1;
48 continue;
49 }
50 break;
51 }
52
53 /* free servinfo */
54 freeaddrinfo(servinfo);
55
56 /* make non-blocking */
57#if !defined(WIN32)
58 if (sockfd != -1) fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFL) | O_NONBLOCK);
59#else
60 if (sockfd != INVALID_SOCKET) {
61 int iMode = 1;
62 ioctlsocket(sockfd, FIONBIO, &iMode);
63 }
64#endif
65#if defined(__VMS)
66 /*
67 OpenVMS only partially implements fcntl. It works on file descriptors
68 but silently fails on socket descriptors. So we need to fall back on
69 to the older ioctl system to set non-blocking IO
70 */
71 int on = 1;
72 if (sockfd != -1) ioctl(sockfd, FIONBIO, &on);
73#endif
74
75 /* return the new socket fd */
76 return sockfd;
77}
78
79#endif
int open_nb_socket(const char *addr, const char *port)