Created
June 23, 2022 19:36
-
-
Save vladiant/0f269fced9331faacaf57cad84280522 to your computer and use it in GitHub Desktop.
C++ TCP Examples
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 <arpa/inet.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <unistd.h> | |
#include <iostream> | |
using namespace std; | |
// Defining Port, Note that port is same on which server is listening and on | |
// which we want to connect | |
#define PORT 9000 | |
/* | |
* This method will create server socket, bind and listen to incomming requests | |
* Parameters | |
* @argc: Number of command line args passed | |
* @*argv[]: Character array containing command line args | |
*/ | |
int main(int argc, char const *argv[]) { | |
int sock = 0, input; | |
struct sockaddr_in serverAddress; // structure for storing address char *msg | |
// = "Hello Server. Its Ninja here"; | |
char buffer[2048] = {0}; | |
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { | |
cout << ("Failed To Create Socket\n"); | |
return -1; | |
} | |
// configuring Address | |
serverAddress.sin_family = AF_INET; | |
serverAddress.sin_port = htons(PORT); | |
// now we will Convert IPv4 and IPv6 addresses from text to binary form | |
if (inet_pton(AF_INET, "127.0.0.1", &serverAddress.sin_addr) <= 0) { | |
cout << ("Invalid address, its not supported"); | |
return -1; | |
} | |
if (connect(sock, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < | |
0) { | |
cout << ("\nConnection with server is Failed \n"); | |
return -1; | |
} | |
cout << "Message sent to server from client"; | |
char *msg = "Hello Ninja. Its Client here"; | |
send(sock, msg, strlen(msg), 0); | |
// now we will read message | |
input = read(sock, buffer, 2048); | |
// printing Buffer | |
cout << ("%s\n", buffer); | |
return 0; | |
} |
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 <netinet/in.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <unistd.h> | |
#include <iostream> | |
using namespace std; // Defining Port | |
#define PORT 9000 | |
/* | |
* This method will create server socket, bind and listen to incomming | |
requests | |
* Parameters | |
* @argc: Number of command line args passed | |
* @*argv[]: Character array containing command line args */ | |
int main(int argc, char const *argv[]) { | |
int serverFileDescriptor, SOCKET, input; | |
struct sockaddr_in address; | |
int opt = 1; | |
int addrlen = sizeof(address); | |
char buffer[1024] = {0}; | |
char *msg = "Hello Ninja. Its Server here"; | |
// Creating socket file descriptor | |
if ((serverFileDescriptor = socket(AF_INET, SOCK_STREAM, 0)) == 0) { | |
perror("Failed to create socket"); | |
exit(EXIT_FAILURE); | |
} | |
// No we will attach socket to the port 9000 | |
if (setsockopt(serverFileDescriptor, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, | |
&opt, sizeof(opt))) { | |
perror("Failed to set socket options"); | |
exit(EXIT_FAILURE); | |
} | |
// Configuring Address | |
address.sin_family = AF_INET; | |
address.sin_addr.s_addr = INADDR_ANY; | |
address.sin_port = htons(PORT); | |
// Forcefully attaching socket to the port 8080 | |
if (bind(serverFileDescriptor, (struct sockaddr *)&address, sizeof(address)) < | |
0) { | |
perror("Server BINDING Failed"); | |
exit(EXIT_FAILURE); | |
} | |
// Now we will listen to incoming requests | |
if (listen(serverFileDescriptor, 3) < 0) { | |
perror("Failed when listening..."); | |
exit(EXIT_FAILURE); | |
} | |
if ((SOCKET = accept(serverFileDescriptor, (struct sockaddr *)&address, | |
(socklen_t *)&addrlen)) < 0) { | |
perror("Failed to accept incoming request"); | |
exit(EXIT_FAILURE); | |
} | |
input = read(SOCKET, buffer, 1024); | |
cout << buffer << endl; | |
cout << "Sending Message to clients..."; | |
send(SOCKET, msg, strlen(msg), 0); | |
return 0; | |
} |
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
// https://simpledevcode.wordpress.com/2016/06/16/client-server-chat-in-c-using-sockets/ | |
#include <arpa/inet.h> | |
#include <fcntl.h> | |
#include <netdb.h> | |
#include <netinet/in.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <sys/time.h> | |
#include <sys/types.h> | |
#include <sys/uio.h> | |
#include <sys/wait.h> | |
#include <unistd.h> | |
#include <fstream> | |
#include <iostream> | |
#include <string> | |
using namespace std; | |
// Client side | |
int main(int argc, char *argv[]) { | |
// we need 2 things: ip address and port number, in that order | |
if (argc != 3) { | |
cerr << "Usage: ip_address port" << endl; | |
exit(0); | |
} // grab the IP address and port number | |
char *serverIp = argv[1]; | |
int port = atoi(argv[2]); | |
// create a message buffer | |
char msg[1500]; | |
// setup a socket and connection tools | |
struct hostent *host = gethostbyname(serverIp); | |
sockaddr_in sendSockAddr; | |
bzero((char *)&sendSockAddr, sizeof(sendSockAddr)); | |
sendSockAddr.sin_family = AF_INET; | |
sendSockAddr.sin_addr.s_addr = | |
inet_addr(inet_ntoa(*(struct in_addr *)*host->h_addr_list)); | |
sendSockAddr.sin_port = htons(port); | |
int clientSd = socket(AF_INET, SOCK_STREAM, 0); | |
// try to connect... | |
int status = | |
connect(clientSd, (sockaddr *)&sendSockAddr, sizeof(sendSockAddr)); | |
if (status < 0) { | |
cout << "Error connecting to socket!" << endl; | |
return EXIT_FAILURE; | |
} | |
cout << "Connected to the server!" << endl; | |
int bytesRead, bytesWritten = 0; | |
struct timeval start1, end1; | |
gettimeofday(&start1, NULL); | |
while (1) { | |
cout << ">"; | |
string data; | |
getline(cin, data); | |
memset(&msg, 0, sizeof(msg)); // clear the buffer | |
strcpy(msg, data.c_str()); | |
if (data == "exit") { | |
send(clientSd, (char *)&msg, strlen(msg), 0); | |
break; | |
} | |
bytesWritten += send(clientSd, (char *)&msg, strlen(msg), 0); | |
cout << "Awaiting server response..." << endl; | |
memset(&msg, 0, sizeof(msg)); // clear the buffer | |
bytesRead += recv(clientSd, (char *)&msg, sizeof(msg), 0); | |
if (!strcmp(msg, "exit")) { | |
cout << "Server has quit the session" << endl; | |
break; | |
} | |
cout << "Server: " << msg << endl; | |
} | |
gettimeofday(&end1, NULL); | |
close(clientSd); | |
cout << "********Session********" << endl; | |
cout << "Bytes written: " << bytesWritten << " Bytes read: " << bytesRead | |
<< endl; | |
cout << "Elapsed time: " << (end1.tv_sec - start1.tv_sec) << " secs" << endl; | |
cout << "Connection closed" << endl; | |
return 0; | |
} |
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
// https://simpledevcode.wordpress.com/2016/06/16/client-server-chat-in-c-using-sockets/ | |
#include <arpa/inet.h> | |
#include <fcntl.h> | |
#include <netdb.h> | |
#include <netinet/in.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <sys/time.h> | |
#include <sys/types.h> | |
#include <sys/uio.h> | |
#include <sys/wait.h> | |
#include <unistd.h> | |
#include <fstream> | |
#include <iostream> | |
#include <string> | |
using namespace std; | |
// Server side | |
int main(int argc, char *argv[]) { | |
// for the server, we only need to specify a port number | |
if (argc != 2) { | |
cerr << "Usage: port" << endl; | |
exit(0); | |
} | |
// grab the port number | |
int port = atoi(argv[1]); | |
// buffer to send and receive messages with | |
char msg[1500]; | |
// setup a socket and connection tools | |
sockaddr_in servAddr; | |
bzero((char *)&servAddr, sizeof(servAddr)); | |
servAddr.sin_family = AF_INET; | |
servAddr.sin_addr.s_addr = htonl(INADDR_ANY); | |
servAddr.sin_port = htons(port); | |
// open stream oriented socket with internet address | |
// also keep track of the socket descriptor | |
int serverSd = socket(AF_INET, SOCK_STREAM, 0); | |
if (serverSd < 0) { | |
cerr << "Error establishing the server socket" << endl; | |
exit(0); | |
} | |
// bind the socket to its local address | |
int bindStatus = | |
bind(serverSd, (struct sockaddr *)&servAddr, sizeof(servAddr)); | |
if (bindStatus < 0) { | |
cerr << "Error binding socket to local address" << endl; | |
exit(0); | |
} | |
cout << "Waiting for a client to connect..." << endl; | |
// listen for up to 5 requests at a time | |
listen(serverSd, 5); | |
// receive a request from client using accept | |
// we need a new address to connect with the client | |
sockaddr_in newSockAddr; | |
socklen_t newSockAddrSize = sizeof(newSockAddr); | |
// accept, create a new socket descriptor to | |
// handle the new connection with client | |
int newSd = accept(serverSd, (sockaddr *)&newSockAddr, &newSockAddrSize); | |
if (newSd < 0) { | |
cerr << "Error accepting request from client!" << endl; | |
exit(1); | |
} | |
cout << "Connected with client!" << endl; | |
// lets keep track of the session time | |
struct timeval start1, end1; | |
gettimeofday(&start1, NULL); | |
// also keep track of the amount of data sent as well | |
int bytesRead, bytesWritten = 0; | |
while (1) { | |
// receive a message from the client (listen) | |
cout << "Awaiting client response..." << endl; | |
memset(&msg, 0, sizeof(msg)); // clear the buffer | |
bytesRead += recv(newSd, (char *)&msg, sizeof(msg), 0); | |
if (!strcmp(msg, "exit")) { | |
cout << "Client has quit the session" << endl; | |
break; | |
} | |
cout << "Client: " << msg << endl; | |
cout << ">"; | |
string data; | |
getline(cin, data); | |
memset(&msg, 0, sizeof(msg)); // clear the buffer | |
strcpy(msg, data.c_str()); | |
if (data == "exit") { | |
// send to the client that server has closed the connection | |
send(newSd, (char *)&msg, strlen(msg), 0); | |
break; | |
} | |
// send the message to client | |
bytesWritten += send(newSd, (char *)&msg, strlen(msg), 0); | |
} | |
// we need to close the socket descriptors after we're all done | |
gettimeofday(&end1, NULL); | |
close(newSd); | |
close(serverSd); | |
cout << "********Session********" << endl; | |
cout << "Bytes written: " << bytesWritten << " Bytes read: " << bytesRead | |
<< endl; | |
cout << "Elapsed time: " << (end1.tv_sec - start1.tv_sec) << " secs" << endl; | |
cout << "Connection closed..." << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment