View difference between Paste ID: TrmK6vrX and 3F9A4xEj
SHOW: | | - or go back to the newest paste.
1
2
/* This code is derived from the CMPS 376 networking code by Marc Thomas
3
 *
4
 * The purpose of this code is to create a very simple Internet server which
5
 * binds to a port, does a simple handshake with the client and then echos
6
 * everything the client sends to the screen.
7
 *
8
 * Command line usage:
9
 *   $ vcrec [packet_size] &
10
 *
11
 *   if packet_size is specified, it must be a positive integer and only that
12
 *   many bytes will be read from the client.
13
 *
14
 * TCP/IP socket functions used by this program:
15
 *
16
 *   socket()        Create a byte stream for client connection requests
17
 *   bind()          Bind the socket to IP address and request TCP port number
18
 *   getsockname()   Query what port number the system assigned to the process
19
 *   listen()        Wait for a client to issue a connection request
20
 *   accept()        Accept the connection request from a client
21
 *   send()          Send data to the client
22
 *   recv()          Receive data from the client
23
 *   close()         Close the sockets
24
 *
25
 * Connection process:
26
 *
27
 * vcsend                      vcrec
28
 * -------------------------   -------------------------
29
 *
30
 * socket() (client socket)    socket() (listen socket)
31
 *                             bind()
32
 *                             getsockname()
33
 *                             listen()
34
 * connect() --------------->  accept() (creates 2nd data socket)
35
 *
36
 * (data exchange phase can be response-driven but if more
37
 *  than one descriptor must be managed use of select() is
38
 *  strongly recommended)
39
 *
40
 * send() --------------------> recv()
41
 * recv() <-------------------- send()
42
 *
43
 * close() (client socket)     close() (both data and listen socket)
44
*/
45
46
47
#include <stdio.h>
48
#include <stdlib.h>
49
#include <string.h>
50
#include <sys/types.h>
51
#include <sys/socket.h>
52
#include <sys/time.h>
53
#include <unistd.h>      /* for gethostname() */
54
#include <arpa/inet.h>   /* for IP address structures and functions */
55
#include <netdb.h>
56
57
58
int main(int argc, char *argv[], char *envp[])
59
{
60
        int     sock, msgsock;  /* Sockets are integer file descriptors on Linux */
61
        struct  sockaddr_in name, caller;
62
        struct  hostent *hp;
63
        char    buf[2048], chrline[80];
64
        int     size, length, ret, k, i; /* Process the command line for the buffer size, if given */
65
        if (argc > 1)
66
        {
67
                size = atoi(argv[1]);
68
    /* Validate that the given argument is between 1 and sizeof(buf) - 1
69
     * Set to the default size if argument is invalid */
70
                if (size < 1  ||  size > sizeof(buf) - 1)
71
                        size = sizeof(buf) - 1;
72
        }
73
        else
74
        {
75
                size = sizeof(buf) - 1;  /* Default size */
76
        }
77
78
79
  /* Create the listen socket. This is a TCP socket, so use SOCK_STREAM
80
   * Exit if the socket cannot be created */
81
        sock = socket(AF_INET, SOCK_STREAM, 0);
82
        if (sock < 0)
83
        {
84
                perror("receiver: socket() failed. ");
85
                return (-1);
86
        }
87
88
  /* Bind the socket to an IP address and port. We will use the IP address
89
   * INADDR_ANY, which tells the system to assign the IP address, and the
90
   * port number 0, which tells the system to assign a random port number.
91
   *
92
   * First we have to set the fields in the sockaddr_in object "name" and then
93
   * we can call bind(). Again, exit if bind() fails. */
94
        name.sin_family = AF_INET;         /* TCP/IP family */
95
        name.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY = assigned by system */
96
        name.sin_port = htons(0);                /* 0 = assigned by system */
97
        ret = bind(sock,(struct sockaddr *)&name,sizeof name);
98
        if (ret < 0)
99
        {
100
                perror("receiver: bind() failed. ");
101
                return (-1);
102
        }
103
104
  /* In order to use vcsend to send data to this program, we need to know
105
   * what port number the system just assigned this program. So this segment
106
   * calls getsockname() to update the sockaddr_in object "name" with the
107
   * system assigned values and then print that info to the screen. */
108
        length = sizeof name;
109
        ret = getsockname(sock, (struct sockaddr *)&name, (socklen_t *)&length);
110
        if (ret < 0)
111
        {
112
                perror("receiver: getsockname() failed. ");
113
                return (-1);
114
        }
115
116
        sleep(1);       /* pause for clean screen display */
117
        printf("\nreceiver: process id: %d ", (int)getpid());
118
        printf("\nreceiver: IP address: %d.%d.%d.%d",
119
        (ntohl(name.sin_addr.s_addr) & 0xff000000) >> 24,
120
        (ntohl(name.sin_addr.s_addr) & 0x00ff0000) >> 16,
121
        (ntohl(name.sin_addr.s_addr) & 0x0000ff00) >>  8,
122
        (ntohl(name.sin_addr.s_addr) & 0x000000ff));
123
        printf("\nreceiver: port number: %hu", ntohs(name.sin_port));
124
        printf("\n");
125
 fflush(stdout);
126
127
  /* Now we will call listen() and wait for a client to connect. The
128
   * accept() function will block until there is a client or an error. */
129
130
        listen(sock,5);         /* up to 5 clients can connect. only 1st is accepted */
131
        k = sizeof caller;
132
        msgsock = accept(sock, (struct sockaddr *)&caller, (socklen_t *)&k);
133
134
  /* We only reach this point when there is an error or a client. We can
135
   * check the value of msgsock (the data socket) to see which has happened */
136
137
        if (msgsock == -1)
138
        {
139
                perror("receiver: accept() failed. ");
140
        }
141
        else
142
  {
143
    printf("\nreceiver: Valid connection received.\n");
144
    printf("receiver: Sending handshake.\n");
145
          fflush(stdout);
146
147
                /* let vcsend know we are ready by sending a single character */
148
          buf[0]= '0';
149
          send(msgsock, buf, 1, 0);
150
151
    printf("receiver: Waiting for client....\n");
152
153
          do    {
154
                        bzero(buf,sizeof buf);  /* zero buffer to remove old data */
155
156
      /* recv() will block until the client sends information, the client
157
       * closes the connection or an error occurs on the data socket. */
158
                        ret = recv(msgsock, buf, size, 0);
159
                        if (ret < 0)
160
                        {
161
                                perror("receiver: recv() failed. ");
162
                        }
163
                        if (ret == 0)
164
                        {
165
                    printf("        received-->sender has ended connection \n");
166
                        }
167
                        else
168
                        {
169
                                printf("        received-->%s \n",buf);
170
                        }
171
172
                        //recv(msgsock, chrline, sizeof(chrline) - 1, 0); /*Handshake character*/
173
                        printf("enter line2> ");
174
                        /* Read input from user */
175
                        fgets(chrline, sizeof(chrline) - 1, stdin);
176
                        printf("FINISHED fgets recieve");
177
                        /* Check for the period to end the connection and also convert any
178
                        * newlines into null characters */
179
                        for (i = 0 ; i < (sizeof(chrline) - 1) ; i++)
180
                        {
181
                         printf("entered for loop recieve");
182
                         if ( (chrline[i] == '\n') || (chrline[i] == '\0') )
183
                            break;
184
                        }
185
                        if (chrline[i] == '\n')
186
 {
187
                          printf("entered if loop1 recieve");
188
                          chrline[i] = '\0';    /* get rid of newline */
189
                        }
190
                        length = strlen(chrline);
191
                        if (chrline[0] == '.')          /* end of stream */
192
                        {
193
                          printf("entered if loop 2 recieve");
194
                          printf("sender: termination requested \n");
195
                          break; /* Exit out of loop */
196
                        }
197
198
                          ret = send(msgsock, chrline, length + 1, 0);
199
200
                        if (ret < 0)
201
                        {
202
                          perror("sender: write() failed. ");
203
                          break;  /* Exit out of loop */
204
                        }
205
                } while (ret != 0); /* Exit loop only when client ends connection */
206
        }
207
208
  /* When we exit the recv() loop, the client has ended the connection, so
209
   * all that remains is closing the sockets. */
210
211
        printf("receiver: ending session also and exiting. \n");
212
        close(msgsock);         /* close data socket */
213
        close(sock);      /* close listen socket */
214
215
        return (0);
216
}  /* end of main */