Created
October 29, 2018 16:03
-
-
Save amithkk/60aeda0148e71934331a6ebde35d2909 to your computer and use it in GitHub Desktop.
Server and Client Programs for Socket Use (TCP) with no error handling
This file contains 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
#include <stdio.h> | |
#include <sys/socket.h> | |
#include <stdlib.h> | |
#include <netinet/in.h> | |
#include <string.h> | |
int main() | |
{ | |
struct sockaddr_in serv_addr; // Structure To Store Internet Address | |
char *msg = "Hey From Client!"; // Message we want to send | |
int sock = socket(AF_INET, SOCK_STREAM, 0); // Create a TCP Socket | |
memset(&serv_addr, '0', sizeof(serv_addr)); // nullchar entire serv addr to get rid of garbage | |
serv_addr.sin_family = AF_INET; // Type of Connection -> Internet | |
serv_addr.sin_port = htons(8080); // Change to network byte order (big-endian) | |
inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr); // converts an Internet address in its standard text format into its numeric binary form | |
connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); // Connect to 127.0.0.1;8080 | |
while(1) | |
{ | |
send(sock, msg, strlen(msg), 0);// Send Our Message | |
sleep(2);// Wait a while | |
} | |
} |
This file contains 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
#include <unistd.h> | |
#include <stdio.h> | |
#include <sys/socket.h> | |
#include <stdlib.h> | |
#include <netinet/in.h> | |
#include <string.h> | |
int main() | |
{ | |
int server_fd, sock; | |
struct sockaddr_in addr; // Address of server | |
int opt = 1; // for getting opt | |
int addrlen = sizeof(addr); // to store addrlen if modified | |
char buffer[512] = {0}; // initialise buffer to 0 | |
server_fd = socket(AF_INET, SOCK_STREAM, 0); //Make a TCP Socket | |
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)); // Allow rebind even if packets are held | |
addr.sin_family = AF_INET; // Type -> Internet Socket | |
addr.sin_addr.s_addr = INADDR_ANY; // Accept connections from anyone | |
addr.sin_port = htons(8080); // Change to network byte order (big-endian) | |
bind(server_fd, (struct sockaddr *)&addr, addrlen); // Tell system we are taking this port (8080) | |
listen(server_fd, 3); // Listen to connections from this socket | |
sock = accept(server_fd, (struct sockaddr *)&addr, (socklen_t*)&addrlen); //Accept first client that connects | |
while(1) | |
{ | |
recv(sock, buffer, 512, 0); //Recieve Data into buffer | |
printf("%s\n", buffer); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment