21 #include <sys/socket.h>
22 #include <arpa/inet.h>
40 struct sockaddr_in server_addr;
41 struct hostent *host_0;
42 struct in_addr *addr_ptr;
43 if (inet_addr(host) == INADDR_NONE) {
44 host_0 = (
struct hostent *)gethostbyname(host);
46 std::cerr <<
"Connect::connectToServer(const char *, int) -> can not get host" << std::endl;
49 addr_ptr = (
struct in_addr *)(*host_0->h_addr_list);
50 host = inet_ntoa(*addr_ptr);
53 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
55 std::cerr <<
"Connect::connectToServer(const char *, int) -> can not open socket" << std::endl;
58 bzero(&server_addr,
sizeof(server_addr));
59 server_addr.sin_family = AF_INET;
60 server_addr.sin_port = htons(0);
61 sock.
server.sin_addr.s_addr = htonl(INADDR_ANY);
62 if (bind(sockfd, (
struct sockaddr *)&server_addr,
sizeof(server_addr)) < 0) {
63 std::cerr <<
"Connect:connectToServer(const char *, int) -> can not bind host" << std::endl;
87 int size = msg.size() + 1;
89 std::cerr <<
"Connect::sendMessage(string) -> error sending message" << std::endl;
98 struct sockaddr_in serv_addr;
99 servlen =
sizeof(serv_addr);
100 if (recvfrom(
sock.
socketfd, msg, 4096, 0, (
struct sockaddr *)&serv_addr, &servlen) < 0) {
101 std::cerr <<
"Connect::receiveMessage() -> error reading message" << std::endl;
102 return "(error socket_failed)";
104 if (
sock.
server.sin_port != serv_addr.sin_port) {
107 return std::string(msg);
struct sockaddr_in server
Connect(const char *host, int port)
bool sendMessage(std::string msg)
void connectToServer(const char *host, int port)
std::string receiveMessage()