Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // SERVER SIDE :
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <arpa/inet.h>
- int main(){
- char *ip = "127.0.0.1";
- int port = 5566;
- int server_sock, client_sock;
- struct sockaddr_in server_addr, client_addr;
- socklen_t addr_size;
- char buffer[1024];
- int n;
- server_sock = socket(AF_INET, SOCK_STREAM, 0);
- if (server_sock < 0){
- perror("Socket error");
- exit(1);
- }
- printf("TCP server socket created.\n");
- memset(&server_addr, '\0', sizeof(server_addr));
- server_addr.sin_family = AF_INET;
- server_addr.sin_port = port;
- server_addr.sin_addr.s_addr = inet_addr(ip);
- n = bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
- if (n < 0){
- perror("Bind error");
- exit(1);
- }
- printf("Bind to the port number: %d\n", port);
- listen(server_sock, 5);
- printf("Listening...\n");
- while(1){
- addr_size = sizeof(client_addr);
- client_sock = accept(server_sock, (struct sockaddr*)&client_addr, &addr_size);
- printf("Client connected.\n");
- bzero(buffer, 1024);
- recv(client_sock, buffer, sizeof(buffer), 0);
- printf("Client: %s\n", buffer);
- bzero(buffer, 1024);
- printf("Enter the Response.\n");
- gets(buffer);
- printf("Server: %s\n", buffer);
- send(client_sock, buffer, strlen(buffer), 0);
- close(client_sock);
- printf("Client disconnected.\n\n");
- }
- return 0;
- }
- // CLIENT SIDE:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <arpa/inet.h>
- int main(){
- char *ip = "127.0.0.1";
- int port = 5566;
- int sock;
- struct sockaddr_in addr;
- socklen_t addr_size;
- char buffer[1024];
- int n;
- sock = socket(AF_INET, SOCK_STREAM, 0);
- if (sock < 0){
- perror("Socket error");
- exit(1);
- }
- printf("TCP server socket created.\n");
- memset(&addr, '\0', sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_port = port;
- addr.sin_addr.s_addr = inet_addr(ip);
- connect(sock, (struct sockaddr*)&addr, sizeof(addr));
- printf("Connected to the server.\n");
- printf("Enter the message to send.\n");
- bzero(buffer, 1024);
- gets(buffer);
- printf("Client: %s\n", buffer);
- send(sock, buffer, strlen(buffer), 0);
- bzero(buffer, 1024);
- recv(sock, buffer, sizeof(buffer), 0);
- printf("Server: %s\n", buffer);
- close(sock);
- printf("Disconnected from the server.\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement