2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17 * Copyright (C) 1998-1999 The Jabber Team http://jabber.org/
24 * Simple wrapper to make socket creation easy.
25 * type = NETSOCKET_SERVER is local listening socket
26 * type = NETSOCKET_CLIENT is connection socket
27 * type = NETSOCKET_UDP
30 int make_netsocket(u_short port
, char *host
, int type
)
33 struct sockaddr_in sa
;
34 struct in_addr
*saddr
;
37 /* is this a UDP socket or a TCP socket? */
38 socket_type
= (type
== NETSOCKET_UDP
)?SOCK_DGRAM
:SOCK_STREAM
;
40 bzero((void *)&sa
,sizeof(struct sockaddr_in
));
42 if((s
= socket(AF_INET
,socket_type
,0)) < 0)
44 if(setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(flag
)) < 0)
47 saddr
= make_addr(host
);
50 sa
.sin_family
= AF_INET
;
51 sa
.sin_port
= htons(port
);
53 if(type
== NETSOCKET_SERVER
)
55 /* bind to specific address if specified */
57 sa
.sin_addr
.s_addr
= saddr
->s_addr
;
59 if(bind(s
,(struct sockaddr
*)&sa
,sizeof sa
) < 0)
65 if(type
== NETSOCKET_CLIENT
)
67 sa
.sin_addr
.s_addr
= saddr
->s_addr
;
68 if(connect(s
,(struct sockaddr
*)&sa
,sizeof sa
) < 0)
74 if(type
== NETSOCKET_UDP
)
76 /* bind to all addresses for now */
77 if(bind(s
,(struct sockaddr
*)&sa
,sizeof sa
) < 0)
83 /* specify default recipient for read/write */
84 sa
.sin_addr
.s_addr
= saddr
->s_addr
;
85 if(connect(s
,(struct sockaddr
*)&sa
,sizeof sa
) < 0)
97 struct in_addr
*make_addr(char *host
)
100 static struct in_addr addr
;
101 char myname
[MAXHOSTNAMELEN
+ 1];
103 if(host
== NULL
|| strlen(host
) == 0)
105 gethostname(myname
,MAXHOSTNAMELEN
);
106 hp
= gethostbyname(myname
);
109 return (struct in_addr
*) *hp
->h_addr_list
;
112 addr
.s_addr
= inet_addr(host
);
113 if(addr
.s_addr
!= -1)
117 hp
= gethostbyname(host
);
120 return (struct in_addr
*) *hp
->h_addr_list
;
126 /* Sets a file descriptor to close on exec. "flag" is 1 to close on exec, 0 to
127 * leave open across exec.
130 int set_fd_close_on_exec(int fd
, int flag
)
132 int oldflags
= fcntl(fd
,F_GETFL
);
136 newflags
= oldflags
| FD_CLOEXEC
;
138 newflags
= oldflags
& (~FD_CLOEXEC
);
140 if(newflags
==oldflags
)
142 return fcntl(fd
,F_SETFL
,(long)newflags
);