You are on page 1of 2

#include <stdio.

h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void DieWithError(char *errorMessage); // error handling function

struct message {

int state;
char msg[20];
};

int main (int argc, char *argv[]) {

int sock; // socket descriptor


int sock2;
struct sockaddr_in echoServAddr; /* Echo server address */
struct sockaddr_in echoServAddr2; /* Echo server address */

unsigned short echoServPort; /* Echo server port */


unsigned short echoServPort2; /* Echo server port */
char *servIP; /* Echo server IP */
char *echoString; /* String to send to Echo server */
int bytesRcvd, totalBytesRcvd; /* Bytes read in single recv() and total
bytes read */
struct message MSG;

if ((argc < 3) || (argc > 5) ) {


fprintf(stderr, "Usage: %s <Server IP> <Echo Word> <Echo Port>\n", argv[0]);
exit(0);
}

MSG.state = 1;
servIP = argv[1];
// echoString = argv[2];

//MSG.msg = argv[2];
strcpy( MSG.msg, argv[2] );
printf("%s",MSG.msg);

if (argc == 5) {
echoServPort = atoi(argv[3]);
echoServPort2 = atoi(argv[4]);
}
else
echoServPort = 7; /* default port */

/* Create a realiable stream socket using TCP */

if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)


DieWithError("socket() failed");

if ((sock2 = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)


DieWithError("socket() failed");

/* Create the server address structure */

memset(&echoServAddr, 0, sizeof(echoServAddr));
echoServAddr.sin_family = AF_INET; /* Internet family address */
echoServAddr.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */
echoServAddr.sin_port = htons(echoServPort); /* Server Port */

memset(&echoServAddr2, 0, sizeof(echoServAddr2));
echoServAddr2.sin_family = AF_INET; /* Internet family address */
echoServAddr2.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */
echoServAddr2.sin_port = htons(echoServPort2); /* Server Port */

/* Establish the connection with echo server */

if (connect(sock, (struct sockaddr *)&echoServAddr, sizeof(echoServAddr)) < 0)


DieWithError("connect() failed 1");

if (connect(sock2, (struct sockaddr *)&echoServAddr2, sizeof(echoServAddr2)) < 0)


DieWithError("connect() failed 2");

/* Estabish the connection to the echo server */

if (send(sock, &MSG, sizeof(MSG), 0) != sizeof(MSG))


DieWithError("send() sent a different number of bytes than expected");

if (send(sock2, &MSG, sizeof(MSG), 0) != sizeof(MSG))


DieWithError("send() sent a different number of bytes than expected");

close (sock);
close (sock2);
exit(0);
return 0;