Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstring>
- #include <iostream>
- #include <netinet/in.h>
- #include <sys/socket.h>
- #include <unistd.h>
- #include <string>
- #include <arpa/inet.h>
- #define IP "127.0.0.1"
- #define PORT 3310
- #define BUFFER_SIZE 1024
- using namespace std;
- int main()
- {
- // Creating socket
- int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
- if (clientSocket == -1) {
- cerr << "Failed to create socket" << endl;
- return 1;
- }
- // Specifying server address
- sockaddr_in serverAddress;
- serverAddress.sin_family = AF_INET;//IPV4
- serverAddress.sin_port = htons(PORT);
- serverAddress.sin_addr.s_addr = inet_addr(IP);
- // Sending connection request
- if (connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) == -1) {
- cerr << "Connection failed to " << IP<<":"<<PORT<< endl;
- close(clientSocket);
- return 1;
- }
- cout << "Connected to server" <<IP<<":"<<PORT<< endl;
- // Sending data
- const char* message = "PING\n";
- if (send(clientSocket, message, strlen(message), 0) == -1) {
- cerr << "Failed to send message" << endl;
- close(clientSocket);
- return 1;
- }
- // cout << "Message sent: " << message<<end;
- // Receiving response
- char buffer[BUFFER_SIZE] = {0};
- int bytesReceived = recv(clientSocket, buffer, BUFFER_SIZE - 1, 0);
- if (bytesReceived == -1) {
- cerr << "Failed to receive response" << endl;
- } else if (bytesReceived == 0) {
- cout << "Server closed the connection" << endl;
- } else {
- cout <<"Response received: " << buffer<< " , Bytes Rx :" << bytesReceived<<endl;
- }
- // Closing socket
- close(clientSocket);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement