-
Notifications
You must be signed in to change notification settings - Fork 0
/
getsockipmtu.c
137 lines (110 loc) · 2.14 KB
/
getsockipmtu.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#ifdef __linux__
/*
* /usr/include/linux/in.h
*/
#define IP_MTU 14
int getsockipmtu(int sockfd)
{
int ret;
unsigned int mtu;
socklen_t len = sizeof(mtu);
ret = getsockopt(sockfd, SOL_IP, IP_MTU, &mtu, &len);
return ret < 0 ? -1 : mtu;
}
#else
int getsockipmtu(int sockfd)
{
return -1;
}
#endif
// Test program
#include <stdio.h>
#include <err.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
static void die(const char *error, ...)
{
va_list param;
va_start(param, error);
verrx(EXIT_FAILURE, error, param);
va_end(param);
}
static char *host = "127.0.0.1";
static char *port = "80";
static void parse_options(int argc, char **argv)
{
int c;
while ((c = getopt(argc, argv, "h:p:")) != -1) {
switch(c) {
case 'h':
host = optarg;
break;
case 'p':
port = optarg;
break;
default:
die("Invalid option %c", c);
break;
}
}
}
/*
* git/connect.c
*/
static int tcp_connect_sock(char *host, char *port)
{
int sockfd;
int saved_errno;
struct addrinfo hints, *ai0, *ai;
int ret;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
ret = getaddrinfo(host, port, &hints, &ai);
if (ret) {
die("Unable to look up %s (port %s) (%s)",
host, port, gai_strerror(ret));
}
for (ai0 = ai; ai; ai = ai->ai_next) {
sockfd = socket(ai->ai_family,
ai->ai_socktype, ai->ai_protocol);
if (sockfd < 0) {
saved_errno = errno;
continue;
}
ret = connect(sockfd, ai->ai_addr, ai->ai_addrlen);
if (ret < 0) {
saved_errno = errno;
close(sockfd);
sockfd = -1;
continue;
}
break;
}
freeaddrinfo(ai0);
if (sockfd < 0)
die("unable to connect a socket (%s)", strerror(saved_errno));
return sockfd;
}
int main(int argc, char **argv)
{
int sockfd;
int mtu;
parse_options(argc, argv);
sockfd = tcp_connect_sock(host, port);
mtu = getsockipmtu(sockfd);
if (mtu < 0)
die("unable to get mtu (%s)", strerror(errno));
printf("%d\n", mtu);
close(sockfd);
return 0;
}