refactored notify.c for clarity
[irssi-notify.git] / notify.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <errno.h>
5 #include <string.h>
6 #include <netdb.h>
7 #include <sys/types.h>
8 #include <netinet/in.h>
9 #include <sys/socket.h>
10
11 #include <arpa/inet.h>
12
13 #define PORT "3490"
14 #define MAX_MSG_ACCEPT_BYTES 100
15
16 // look for an IPv4/6 host:port in an address structure
17 void *get_in_addr(struct sockaddr *sa)
18 {
19 if (sa->sa_family == AF_INET) {
20 return &(((struct sockaddr_in*)sa)->sin_addr);
21 }
22 return &(((struct sockaddr_in6*)sa)->sin6_addr);
23 }
24
25 int main(int argc, char *argv[])
26 {
27 int sockfd, numbytes;
28 struct addrinfo hints, *servinfo, *port;
29 char s[INET6_ADDRSTRLEN];
30 int rv;
31 char buf[MAX_MSG_ACCEPT_BYTES];
32
33 if (argc != 3) {
34 fprintf(stderr, "usage: client hostname 'message'\n");
35 exit(1);
36 }
37
38 memset(&hints, 0, sizeof hints);
39 hints.ai_family = AF_UNSPEC;
40 hints.ai_socktype = SOCK_STREAM;
41
42 // look up local address information
43 if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) {
44 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
45 return 1;
46 }
47
48 // loop over available interfaces and try to bind to port
49 for(port = servinfo; port != NULL; port = port->ai_next) {
50 if ((sockfd = socket(port->ai_family, port->ai_socktype,
51 port->ai_protocol)) == -1) {
52 perror("client: socket");
53 continue;
54 }
55 if (connect(sockfd, port->ai_addr, port->ai_addrlen) == -1) {
56 close(sockfd);
57 perror("client: connect");
58 continue;
59 }
60 break;
61 }
62
63 if (port == NULL) {
64 fprintf(stderr, "client: failed to connect\n");
65 return 2;
66 }
67
68 if (send(sockfd, argv[2], strlen(argv[2])+1, 0) == -1)
69 perror("send");
70
71 close(sockfd);
72
73 return 0;
74 }