-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconnection.c
71 lines (56 loc) · 1.62 KB
/
connection.c
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
/*
* af_ktls tool
*
* Copyright (C) 2016 Fridolin Pokorny <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*/
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <unistd.h>
#include "connection.h"
extern int udp_connect(const char *host, unsigned port)
{
int err, sd, optval;
struct sockaddr_in sa;
sd = socket(AF_INET, SOCK_DGRAM, 0);
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
inet_pton(AF_INET, host, &sa.sin_addr);
#if defined(IP_DONTFRAG)
optval = 1;
setsockopt(sd, IPPROTO_IP, IP_DONTFRAG, (const void *) &optval, sizeof(optval));
#elif defined(IP_MTU_DISCOVER)
optval = IP_PMTUDISC_DO;
setsockopt(sd, IPPROTO_IP, IP_MTU_DISCOVER, (const void *) &optval, sizeof(optval));
#endif
err = connect(sd, (struct sockaddr *) &sa, sizeof(sa));
return err ? err : sd;
}
extern void udp_close(int sd) {
close(sd);
}
extern int tcp_connect(const char *host, unsigned port) {
int err, sd;
struct sockaddr_in sa;
sd = socket(AF_INET, SOCK_STREAM, 0);
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
inet_pton(AF_INET, host, &sa.sin_addr);
err = connect(sd, (struct sockaddr *) &sa, sizeof(sa));
return err ? err : sd;
}
extern void tcp_close(int sd) {
shutdown(sd, SHUT_RDWR); //no more receptions
close(sd);
}