Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <errno.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <netdb.h>
- #include <string>
- #include <string.h>
- #include <iostream>
- using namespace std;
- extern int errno;
- int port;
- int main(int argc, char *argv[])
- {
- int sd;
- struct sockaddr_in server;
- string input;
- string answer;
- int n;
- char buf[500];
- if(argc!=3)
- {
- cout<<"Sintaxa: "<<argv[0]<<"<adresa_server><port>\n";
- return -1;
- }
- port = atoi(argv[2]);//ascii to integer
- //---->socket()
- if((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
- {
- perror("Socket() error.\n");
- return errno;
- }
- server.sin_family = AF_INET;
- server.sin_addr.s_addr = inet_addr(argv[1]);
- server.sin_port = htons(port); //hostshort to network byte order
- //---->connect()
- if(connect(sd, (struct sockaddr *) &server, sizeof(struct sockaddr)) == -1)
- {
- perror("[client]Connect() error.\n");
- return errno;
- }
- bzero(buf, 500);
- answer.empty();
- input.clear();
- cout<<"[client]Input your name: "<<flush;
- getline(std::cin, input);
- cout<<input;
- if(n = (send(sd, input.data(), input.size(), 0))<0)
- {
- perror("[client]Write to server error.\n");
- return errno;
- }
- while((n = recv(sd, buf, sizeof(buf), 0))>0)
- {
- answer.append(buf, buf+n);
- }
- if(n<0)
- {
- perror("[client]Read from server error.\n");
- return errno;
- }
- cout<<"[client]Received message is: "<<answer<<endl;
- close(sd);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement