1 /*
2 Copyright (c) 2021 Fraunhofer AISEC. See the COPYRIGHT
3 file at the top-level directory of this distribution.
4
5 Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 option. This file may not be copied, modified, or distributed
9 except according to those terms.
10 */
11 #include "sock.h"
12
13 #include <stdio.h>
14 #include <string.h>
15
16 #ifdef LINUX_SOCKETS
17 #include <arpa/inet.h>
18 #include <sys/socket.h>
19 #else
20 #include <zephyr/net/net_pkt.h>
21 #include <zephyr/net/net_if.h>
22 #include <zephyr/net/net_core.h>
23 #include <zephyr/net/net_context.h>
24 #include <zephyr/net/udp.h>
25 #include <zephyr/net/socket.h>
26 #endif
27
ipv6_sock_init(enum sock_type sock_t,const char * ipv6_addr_str,struct sockaddr_in6 * servaddr,size_t servaddr_len,int * sockfd)28 int ipv6_sock_init(enum sock_type sock_t, const char *ipv6_addr_str,
29 struct sockaddr_in6 *servaddr, size_t servaddr_len,
30 int *sockfd)
31 {
32 int r;
33
34 memset(servaddr, 0, servaddr_len);
35
36 /* Creating socket file descriptor */
37 *sockfd = socket(AF_INET6, SOCK_DGRAM, 0);
38 if (*sockfd < 0)
39 return *sockfd;
40
41 servaddr->sin6_family = AF_INET6;
42 servaddr->sin6_port = htons(PORT);
43 r = inet_pton(AF_INET6, ipv6_addr_str, &servaddr->sin6_addr);
44 if (r < 0)
45 return r;
46
47 if (sock_t == SOCK_CLIENT) {
48 r = connect(*sockfd, (const struct sockaddr *)servaddr,
49 servaddr_len);
50 if (r < 0)
51 return r;
52 printf("IPv6 client to connect to server with address %s started!\n",
53 ipv6_addr_str);
54 } else {
55 r = bind(*sockfd, (const struct sockaddr *)servaddr,
56 servaddr_len);
57 if (r < 0)
58 return r;
59
60 printf("IPv6 server with address %s started!\n", ipv6_addr_str);
61 }
62 return 0;
63 }
64