Tizen 2.0 Release
[external/libgnutls26.git] / doc / examples / tcp.c
1 /* This example code is placed in the public domain. */
2
3 #ifdef HAVE_CONFIG_H
4 #include <config.h>
5 #endif
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <arpa/inet.h>
13 #include <netinet/in.h>
14 #include <unistd.h>
15
16 #define SA struct sockaddr
17
18 /* tcp.c */
19 int tcp_connect (void);
20 void tcp_close (int sd);
21
22 /* Connects to the peer and returns a socket
23  * descriptor.
24  */
25 extern int
26 tcp_connect (void)
27 {
28   const char *PORT = "5556";
29   const char *SERVER = "127.0.0.1";
30   int err, sd;
31   struct sockaddr_in sa;
32
33   /* connects to server
34    */
35   sd = socket (AF_INET, SOCK_STREAM, 0);
36
37   memset (&sa, '\0', sizeof (sa));
38   sa.sin_family = AF_INET;
39   sa.sin_port = htons (atoi (PORT));
40   inet_pton (AF_INET, SERVER, &sa.sin_addr);
41
42   err = connect (sd, (SA *) & sa, sizeof (sa));
43   if (err < 0)
44     {
45       fprintf (stderr, "Connect error\n");
46       exit (1);
47     }
48
49   return sd;
50 }
51
52 /* closes the given socket descriptor.
53  */
54 extern void
55 tcp_close (int sd)
56 {
57   shutdown (sd, SHUT_RDWR);     /* no more receptions */
58   close (sd);
59 }