
Untitled
By: a guest on
May 9th, 2012 | syntax:
C | size: 1.79 KB | hits: 31 | expires: Never
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
typedef struct order{
char command;
int param1;
int param2;
} ORDER;
int main(int argc, char *argv[]){
int s;
struct sockaddr_in sa;
struct hostent *hp;
char newline = '\n';
ORDER o ;
if(argc<2){
puts("you must provide a user");
return EXIT_FAILURE;
}
char c;
int a,b;
if(scanf("%c %d %d", &c , &a,&b) < 3){
printf("you need to provide command(+-*/) and two integer numbers");
return EXIT_FAILURE;
}
o.command = c;
o.param1 = a;
o.param2 = b;
if( (hp = gethostbyname("localhost")) == NULL ){
perror("failed to translate the hostname");
return EXIT_FAILURE;
}
bzero( (char *) &sa, sizeof(sa));
sa.sin_family=AF_INET;
bcopy( (char *) hp->h_addr, (char *) &sa.sin_addr.s_addr, hp->h_length);
if( (s = socket(hp->h_addrtype, SOCK_STREAM, 0)) < 0 ){
perror("failed creating the socket");
return EXIT_FAILURE;
}
sa.sin_port=htons(atoi(argv[2]));
if(connect(s,(struct sockaddr *) &sa, sizeof(sa)) < 0 ){
perror("an error has occured while connecting");
return EXIT_FAILURE;
}
if(full_send(s,&o,sizeof(o))<0){
perror("an error has occured while sending the data");
return EXIT_FAILURE;
}
if ( recv(s, &a,sizeof(a),0) != sizeof(a) ){
perror("error while receiving the result");
return EXIT_FAILURE;
}
printf("%d", a);
close(s);
return EXIT_SUCCESS;
}
int full_send(int socket, void* buffer, size_t size){
size_t sent =0 ;
size_t ret;
while(sent < size){
ret = send(socket, buffer+sent, size-sent,0);
if ( ret < 0 ){
return -1;
}else{
sent +=ret;
}
}
return sent;
}