Skip to content

Commit c276ac8

Browse files
committed
Tested TCP echo
1 parent 774641d commit c276ac8

File tree

4 files changed

+72
-0
lines changed

4 files changed

+72
-0
lines changed

Check/TCP/Client

16.6 KB
Binary file not shown.

Check/TCP/Server

16.8 KB
Binary file not shown.

Check/TCP/client.c

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#include<stdio.h>
2+
#include<stdlib.h>
3+
4+
#include<arpa/inet.h>
5+
#include<sys/socket.h>
6+
#include<sys/types.h>
7+
#include<netdb.h>
8+
#include<unistd.h>
9+
#include<fcntl.h>
10+
11+
void main(){
12+
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
13+
14+
struct sockaddr_in serv_addr;
15+
serv_addr.sin_family = AF_INET;
16+
serv_addr.sin_port = htons(8080);
17+
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
18+
19+
int response = connect(sock_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
20+
if (response==0){
21+
printf("\nConnected");
22+
}
23+
24+
int msg_size = -1;
25+
char* msg_buff = (char*)malloc(sizeof(char)*100);
26+
do{
27+
printf("\nEnter Message: ");
28+
scanf(" %s", msg_buff);
29+
msg_size = send(sock_fd, msg_buff, 100, 0);
30+
msg_size = recv(sock_fd, msg_buff, 100, 0);
31+
}while(msg_size!=0);
32+
}

Check/TCP/server.c

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include<stdio.h>
2+
#include<stdlib.h>
3+
4+
#include<arpa/inet.h>
5+
#include<sys/socket.h>
6+
#include<sys/types.h>
7+
#include<netdb.h>
8+
#include<unistd.h>
9+
#include<fcntl.h>
10+
11+
void main(){
12+
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
13+
int true_flag = 1;
14+
setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &true_flag, sizeof(int));
15+
16+
struct sockaddr_in bind_addr;
17+
bind_addr.sin_family = AF_INET;
18+
bind_addr.sin_port = htons(8080);
19+
bind_addr.sin_addr.s_addr = htonl(INADDR_ANY);
20+
bind(sock_fd, (struct sockaddr*)&bind_addr, sizeof(bind_addr));
21+
22+
listen(sock_fd, 5);
23+
24+
struct sockaddr_in client_addr;
25+
int client_addr_size;
26+
int client_fd = accept(sock_fd, (struct sockaddr*)&client_addr, &client_addr_size);
27+
28+
char *client_ip = (char*)malloc(sizeof(char)*100);
29+
inet_ntop(AF_INET, (void*)&client_addr.sin_addr, client_ip, 100);
30+
int client_port = (int)ntohs(client_addr.sin_port);
31+
printf("\n%s\n%d", client_ip, client_port);
32+
33+
int msg_size = -1;
34+
char* msg_buff = (char*)malloc(sizeof(char)*100);
35+
do{
36+
msg_size = recv(client_fd, msg_buff, 100, 0);
37+
printf("\n%s", msg_buff);
38+
msg_size = send(client_fd, msg_buff, 100, 0);
39+
}while(msg_size!=0);
40+
}

0 commit comments

Comments
 (0)