File: addr.c

package info (click to toggle)
tcputils 0.6.2-3
  • links: PTS
  • area: main
  • in suites: potato
  • size: 188 kB
  • ctags: 109
  • sloc: ansic: 1,277; makefile: 100; sh: 46
file content (81 lines) | stat: -rw-r--r-- 1,603 bytes parent folder | download | duplicates (7)
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
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include "ip_misc.h"


#define	Export


/*
 *  Fill in ADDR from HOST, SERVICE and PROTOCOL.
 *  PROTOCOL can be tcp or udp.
 *  Supplying a null pointer for HOST means use INADDR_ANY.
 *  Supplying a null pointer for SERVICE, means use port 0, i.e. no port.
 *
 *  Returns negative on errors, zero or positive if everything ok.
 */
Export	int
get_inaddr(struct sockaddr_in	* addr,
	   const char		* host,
	   const char		* service,
	   const char		* protocol)
{
    memset(addr, 0, sizeof *addr);
    addr->sin_family = AF_INET;

    /*
     *  Set host part of ADDR
     */
    if (host == NULL)
	addr->sin_addr.s_addr = INADDR_ANY;
    else
    {
	addr->sin_addr.s_addr = inet_addr(host);
	if (addr->sin_addr.s_addr == (unsigned long)-1)
	{
	    struct hostent	* hp;

	    hp = gethostbyname(host);
	    if (hp == NULL)
		return -1;
	    memcpy(&addr->sin_addr, hp->h_addr, hp->h_length);
	    addr->sin_family = hp->h_addrtype;
	}
    }

    /*
     *  Set port part of ADDR
     */
    if (service == NULL)
	addr->sin_port = htons(0);
    else
    {
	char		* end;
	long		  portno;

	portno = strtol(service, &end, 10);
	if (portno > 0  &&  portno <= 65535
	    &&  end != service  &&  *end == '\0')
	{
	    addr->sin_port = htons(portno);
	}
	else
	{
	    struct servent	* serv;

	    serv = getservbyname(service, protocol);
	    if (serv == NULL)
		return -1;
	    addr->sin_port = serv->s_port;
	}
    }

    return 0;
}