-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTCP-ClientProgramming.c
More file actions
84 lines (63 loc) · 2.29 KB
/
TCP-ClientProgramming.c
File metadata and controls
84 lines (63 loc) · 2.29 KB
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
82
83
84
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
main(argc, argv)
int argc;
char *argv[];
{
struct sockaddr_in sad; /* structure to hold an IP address */
int clientSocket; /* socket descriptor */
struct hostent *ptrh; /* pointer to a host table entry */
char *host; /* pointer to host name */
int port; /* protocol port number */
char Sentence[128];
char modifiedSentence[128];
char buff[128];
int n;
if (argc != 3) {
fprintf(stderr,"Usage: %s server-name port-number\n",argv[0]);
exit(1);
}
/* Extract host-name from command-line argument */
host = argv[1]; /* if host argument specified */
/* Extract port number from command-line argument */
port = atoi(argv[2]); /* convert to binary */
/* Create a socket. */
clientSocket = socket(PF_INET, SOCK_STREAM, 0);
if (clientSocket < 0) {
fprintf(stderr, "socket creation failed\n");
exit(1);
}
/* Connect the socket to the specified server. */
memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */
sad.sin_family = AF_INET; /* set family to Internet */
sad.sin_port = htons((u_short)port);
ptrh = gethostbyname(host); /* Convert host name to equivalent IP address and copy to sad. */
if ( ((char *)ptrh) == NULL ) {
fprintf(stderr,"invalid host: %s\n", host);
exit(1);
}
memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length);
if (connect(clientSocket, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
fprintf(stderr,"connect failed\n");
exit(1);
}
/* Read a sentence from user */
printf("Sentence : "); gets(Sentence);
/* Send the sentence to the server */
write(clientSocket, Sentence, strlen(Sentence)+1);
/* Get the modified sentence from the server and write it to the screen*/
modifiedSentence[0]='\0';
n=read(clientSocket, buff, sizeof(buff));
while(n > 0){
strncat(modifiedSentence,buff,n);
if (buff[n-1]=='\0') break;
n=read(clientSocket, buff, sizeof(buff));
}
printf("Modified to -> %s\n",modifiedSentence);
/* Close the socket. */
close(clientSocket);
}