util.c 1.63 KB
Newer Older
Dafydd Harries's avatar
Dafydd Harries committed
1
2
3

#include <stdlib.h>

4
#include "agent.h"
Dafydd Harries's avatar
Dafydd Harries committed
5
6
7
8

/* format is:
 *   type/ip/port
 */
9
10
NiceCandidate *
nice_candidate_from_string (const gchar *s)
Dafydd Harries's avatar
Dafydd Harries committed
11
{
12
13
  NiceCandidateType type;
  NiceCandidate *candidate;
Dafydd Harries's avatar
Dafydd Harries committed
14
15
  guint32 ip;
  guint16 port;
16
  gchar **bits;
Dafydd Harries's avatar
Dafydd Harries committed
17
18
19
20

  if (s == NULL || s[0] == '\0')
    return NULL;

21
22
23
24
25
26
  bits = g_strsplit (s, "/", 3);

  if (g_strv_length (bits) != 3)
    return NULL;

  switch (bits[0][0])
Dafydd Harries's avatar
Dafydd Harries committed
27
28
    {
    case 'H':
29
      type = NICE_CANDIDATE_TYPE_HOST;
Dafydd Harries's avatar
Dafydd Harries committed
30
31
      break;
    case 'S':
32
      type = NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE;
Dafydd Harries's avatar
Dafydd Harries committed
33
34
      break;
    case 'P':
35
      type = NICE_CANDIDATE_TYPE_PEER_REFLEXIVE;
Dafydd Harries's avatar
Dafydd Harries committed
36
37
      break;
    case 'R':
38
      type = NICE_CANDIDATE_TYPE_RELAYED;
Dafydd Harries's avatar
Dafydd Harries committed
39
40
41
42
43
44
45
      break;
    default:
      return NULL;
    }

  /* extract IP address */

46
  if (inet_pton (AF_INET, bits[1], &ip) < 1)
Dafydd Harries's avatar
Dafydd Harries committed
47
48
49
50
    return NULL;

  /* extract port */

51
  port = strtol (bits[2], NULL, 10);
Dafydd Harries's avatar
Dafydd Harries committed
52

53
  candidate = nice_candidate_new (type);
54
  nice_address_set_ipv4 (&candidate->addr, ntohl (ip));
Dafydd Harries's avatar
Dafydd Harries committed
55
56
57
58
59
60
  candidate->port = port;

  return candidate;
}

gchar *
61
nice_candidate_to_string (NiceCandidate *candidate)
Dafydd Harries's avatar
Dafydd Harries committed
62
63
64
65
66
67
68
{
  gchar *addr_tmp;
  gchar *ret;
  gchar type;

  switch (candidate->type)
    {
69
    case NICE_CANDIDATE_TYPE_HOST:
Dafydd Harries's avatar
Dafydd Harries committed
70
71
      type = 'H';
      break;
72
    case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE:
Dafydd Harries's avatar
Dafydd Harries committed
73
74
      type = 'S';
      break;
75
    case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE:
Dafydd Harries's avatar
Dafydd Harries committed
76
77
      type = 'P';
      break;
78
    case NICE_CANDIDATE_TYPE_RELAYED:
Dafydd Harries's avatar
Dafydd Harries committed
79
80
81
82
83
84
      type = 'R';
      break;
    default:
      return NULL;
    }

85
  addr_tmp = nice_address_to_string (&(candidate->addr));
Dafydd Harries's avatar
Dafydd Harries committed
86
87
88
89
90
  ret = g_strdup_printf ("%c/%s/%d", type, addr_tmp, candidate->port);
  g_free (addr_tmp);
  return ret;
}