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 #include <arpa/inet.h>
17 #include <sys/socket.h>
18
19 /**
20 * @brief Initializes a IPv4 client or server socket
21 * @param sock_t CLIENT or SERVER
22 * @param ipv6_addr_str ip address as string
23 * @param servaddr address struct
24 * @param servaddr_len length of servaddr
25 * @param sockfd socket file descriptor
26 * @retval error code
27 */
ipv4_sock_init(enum sock_type sock_t,const char * ipv4_addr_str,struct sockaddr_in * servaddr,size_t servaddr_len,int * sockfd)28 int ipv4_sock_init(enum sock_type sock_t, const char *ipv4_addr_str,
29 struct sockaddr_in *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_INET, SOCK_DGRAM, 0);
38 if (*sockfd < 0)
39 return *sockfd;
40
41 servaddr->sin_family = AF_INET;
42 servaddr->sin_port = htons(PORT);
43 servaddr->sin_addr.s_addr = inet_addr(ipv4_addr_str);
44
45 if (sock_t == SOCK_CLIENT) {
46 r = connect(*sockfd, (const struct sockaddr *)servaddr,
47 servaddr_len);
48 if (r < 0) {
49 return r;
50 }
51
52 printf("IPv4 client to connect to server with address %s started!\n",
53 ipv4_addr_str);
54 } else {
55 r = bind(*sockfd, (const struct sockaddr *)servaddr,
56 servaddr_len);
57 if (r < 0) {
58 return r;
59 }
60
61 printf("IPv4 server with address %s started!\n", ipv4_addr_str);
62 }
63 return 0;
64 }
65