Last active
March 2, 2023 10:52
-
-
Save SkrewEverything/2c535e83a3a7b8e5b7aa490009a87fbb to your computer and use it in GitHub Desktop.
Simple TCP server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Server side C program to demonstrate Socket programming | |
| #include <stdio.h> | |
| #include <sys/socket.h> | |
| #include <unistd.h> | |
| #include <stdlib.h> | |
| #include <netinet/in.h> | |
| #include <string.h> | |
| #define PORT 8080 | |
| int main(int argc, char const *argv[]) | |
| { | |
| int server_fd, new_socket; long valread; | |
| struct sockaddr_in address; | |
| int addrlen = sizeof(address); | |
| char *hello = "Hello from server"; | |
| // Creating socket file descriptor | |
| if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) | |
| { | |
| perror("In socket"); | |
| exit(EXIT_FAILURE); | |
| } | |
| address.sin_family = AF_INET; | |
| address.sin_addr.s_addr = INADDR_ANY; | |
| address.sin_port = htons( PORT ); | |
| memset(address.sin_zero, '\0', sizeof address.sin_zero); | |
| if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) | |
| { | |
| perror("In bind"); | |
| exit(EXIT_FAILURE); | |
| } | |
| if (listen(server_fd, 10) < 0) | |
| { | |
| perror("In listen"); | |
| exit(EXIT_FAILURE); | |
| } | |
| while(1) | |
| { | |
| printf("\n+++++++ Waiting for new connection ++++++++\n\n"); | |
| if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) | |
| { | |
| perror("In accept"); | |
| exit(EXIT_FAILURE); | |
| } | |
| char buffer[30000] = {0}; | |
| valread = read( new_socket , buffer, 30000); | |
| printf("%s\n",buffer ); | |
| write(new_socket , hello , strlen(hello)); | |
| printf("------------------Hello message sent-------------------\n"); | |
| close(new_socket); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment