summaryrefslogtreecommitdiff
path: root/src/socket_tcp.c
blob: 866ac19cca8bc66f2d4de298370bbc9bb3c70f67 (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
66
67
68
69
70
71
#include <netinet/in.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/types.h>

#include <errno.h>

#include "close.h" /* better use unistd.h ? */
#include "error.h"
#include "ndelay.h"
#include "socket_if.h"

#ifndef EAFNOSUPPORT
  #define EAFNOSUPPORT EINVAL
#endif

/**
  @file socket_tcp.c
  @authors djb, fefe, feh
  @ref ucspi-tcp6
  @brief setup TCP stream socket
*/

int socket_tcp4(void)
{
  int s = socket(AF_INET, SOCK_STREAM, 0);
  if (s != -1) {
    if (ndelay_on(s) == -1) {
      close(s);
      return -1;
    }
  }

  return s;
}

int socket_tcp6(void)
{
  int s = socket(AF_INET6, SOCK_STREAM, 0);
  if (s != -1) {
    if (ndelay_on(s) == -1) {
      close(s);
      return -1;
    }
  }

  return s;
}

int socket_tcp(void)
{
  int s = socket(AF_INET6, SOCK_STREAM, 0);
  if (s == -1)
    if (errno == EINVAL || errno == EAFNOSUPPORT || errno == EPROTO || errno == EPROTONOSUPPORT)
      s = socket(AF_INET, SOCK_STREAM, 0);

  if (s != -1) {
    if (ndelay_on(s) == -1) {
      close(s);
      return -1;
    }
  }

  return s;
}

int socket_tcpnodelay(int s)
{
  int opt = 1;
  return setsockopt(s, IPPROTO_TCP, 1, &opt, sizeof(opt)); /* 1 == TCP_NODELAY */
}