-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp_client.c
50 lines (44 loc) · 1010 Bytes
/
tcp_client.c
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
/**
* TCP Client Program.
*/
#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define BUF_SIZE 100
int main(){
int port,sd,snd,clientlen,rec,k;
struct sockaddr_in client;
char buf[BUF_SIZE];
printf("Enter the port to be used :");
scanf("%d",&port);
sd = socket(AF_INET,SOCK_STREAM, 0); //Create a socket
if(sd<0){
printf("Unable to create socket\n");
return 0;
}
memset(&client,0,sizeof(client));
client.sin_family=AF_INET;
client.sin_addr.s_addr=inet_addr("127.0.0.1");
client.sin_port=port;
k=connect(sd,(struct sockaddr*)&client,sizeof(client));
if(k<0){
printf("Unable to connect to server.\n");
return 0;
}
printf("Enter message\n");
scanf("%s",buf);
snd=send(sd,buf,BUF_SIZE,0);
if(snd<BUF_SIZE){
printf("Sending failed.\n");
return 0;
}
rec=recv(sd,buf,BUF_SIZE,0);
if(rec<0){
printf("Receiving failed\n");
return 0;
}
printf(">%s\n",buf);
close(sd);
return 0;
}