Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/tests/sys/mac/portacl/bind.c
289261 views
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <string.h>
4
#include <errno.h>
5
#include <unistd.h>
6
#include <sys/types.h>
7
#include <sys/socket.h>
8
#include <netdb.h>
9
10
int main(int argc, char *argv[])
11
{
12
if (argc < 5) {
13
fprintf(stderr, "Usage: %s family host protocol port\n", argv[0]);
14
return 1;
15
}
16
int family = atoi(argv[1]);
17
const char *host = argv[2];
18
const char *protocol = argv[3];
19
const char *port = argv[4];
20
int sock_type;
21
if (strcmp(protocol, "tcp") == 0)
22
sock_type = SOCK_STREAM;
23
else if (strcmp(protocol, "udp") == 0)
24
sock_type = SOCK_DGRAM;
25
else {
26
fprintf(stderr, "Unsupported protocol: %s\n", protocol);
27
return 1;
28
}
29
struct addrinfo hints, *res;
30
memset(&hints, 0, sizeof(hints));
31
hints.ai_family = family;
32
hints.ai_socktype = sock_type;
33
hints.ai_flags = AI_PASSIVE;
34
int err = getaddrinfo(host, port, &hints, &res);
35
if (err != 0) {
36
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(err));
37
return 1;
38
}
39
int sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
40
if (sock < 0) {
41
freeaddrinfo(res);
42
return 1;
43
}
44
int opt = 1;
45
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
46
if (bind(sock, res->ai_addr, res->ai_addrlen) < 0) {
47
if (errno == EACCES || errno == EPERM)
48
printf("bind_error: permission denied.\n");
49
else
50
printf("bind error: %s\n", strerror(errno));
51
close(sock);
52
freeaddrinfo(res);
53
return 1;
54
}
55
printf("ok\n");
56
close(sock);
57
freeaddrinfo(res);
58
return 0;
59
}
60
61
62