Smallish changes.
[yaz-moved-to-github.git] / rfc1006 / makensap.c
1 /*
2  * A quick little implementation of the makensap function of the
3  * xtimosi package. It's needed to make the demo apps work.
4  */
5
6 #include <stdio.h>
7 #include <sys/types.h>
8 #include <errno.h>
9 #include <sys/socket.h>
10 #include <netinet/in.h>
11 #include <arpa/inet.h>
12 #include <netdb.h>
13 #include <string.h>
14 #include <stdlib.h>
15
16 static struct sockaddr_in *tcpip_strtoaddr(const char *str);
17
18 /*
19  * text format is <hostname> | <IP-address> ':' <port>. No spaces.
20  * The binary form is a struct sockaddr_ip.
21  */
22 int makensap(char *text, unsigned char *binary)
23 {
24     struct sockaddr_in *addr;
25
26     fprintf(stderr, "Mapping textform NSAP '%s'\n", text);
27     if (!(addr = tcpip_strtoaddr(text)))
28     {
29         fprintf(stderr, "Failed to resolve '%s'\n", text);
30         return -1;
31     }
32     memcpy(binary, addr, sizeof(struct sockaddr_in));
33     return sizeof(struct sockaddr_in);
34 }
35
36 /*
37  * This is the address mapper from the comstack submodule of YAZ.
38  */
39 static struct sockaddr_in *tcpip_strtoaddr(const char *str)
40 {
41     static struct sockaddr_in add;
42     struct hostent *hp;
43     char *p, buf[512];
44     short int port = 210;
45     unsigned long tmpadd;
46
47     add.sin_family = AF_INET;
48     strcpy(buf, str);
49     if ((p = strchr(buf, ':')))
50     {
51         *p = 0;
52         port = atoi(p + 1);
53     }
54     add.sin_port = htons(port);
55     if ((hp = gethostbyname(buf)))
56         memcpy(&add.sin_addr.s_addr, *hp->h_addr_list, sizeof(struct in_addr));
57     else if ((tmpadd = inet_addr(buf)) != 0)
58         memcpy(&add.sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
59     else
60         return 0;
61     return &add;
62 }