summaryrefslogtreecommitdiff
path: root/src/socket_send.c
blob: 1d0ce566a6ac0a1f352768bc612455629614e536 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <netinet/in.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/types.h>

#include "byte.h"
#include "ip.h"
#include "socket_if.h"

/**
  @file socket_send.c
  @author djb, fefe, feh
  @source ucspi-tcp6
  @brief setup sending socket
*/

int socket_send4(int s, const char *buf, unsigned int len, const char ip[4], uint16 port)
{
  struct sockaddr_in sa;

  byte_zero(&sa, sizeof(sa));

  sa.sin_family = AF_INET;
  uint16_pack_big((char *)&sa.sin_port, port);
  byte_copy((char *)&sa.sin_addr, 4, ip);

  return sendto(s, buf, len, 0, (struct sockaddr *)&sa, sizeof(sa));
}

int socket_send6(
    int s, const char *buf, unsigned int len, const char ip[16], uint16 port, uint32 scope_id)
{
  struct sockaddr_in6 sa;

  byte_zero(&sa, sizeof(sa));

  sa.sin6_family = AF_INET6;
  sa.sin6_scope_id = scope_id;
  uint16_pack_big((char *)&sa.sin6_port, port);
  byte_copy((char *)&sa.sin6_addr, 16, ip);

  return sendto(s, buf, len, 0, (struct sockaddr *)&sa, sizeof(sa));
}

int socket_send(
    int s, const char *buf, unsigned int len, const char ip[16], uint16 port, uint32 scope_id)
{
  if (ip6_isv4mapped(ip))
    return socket_send4(s, buf, len, ip + 12, port);
  else
    return socket_send6(s, buf, len, ip, port, scope_id);
}

int socket_broadcast4(int s, const char *buf, unsigned int len, uint16 port)
{
  struct sockaddr_in sa;

  byte_zero(&sa, sizeof(sa));

  sa.sin_family = AF_INET;
  uint16_pack_big((char *)&sa.sin_port, port);
  byte_copy((char *)&sa.sin_addr, 4, V4broadcast);

  return sendto(s, buf, len, 0, (struct sockaddr *)&sa, sizeof(sa));
}