ffead.server.doc
ClientInterface.cpp
1 /*
2  Copyright 2010, Sumeet Chhetri
3 
4  Licensed under the Apache License, Version 2.0 (the "License");
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7 
8  http://www.apache.org/licenses/LICENSE-2.0
9 
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15 */
16 /*
17  * ClientInterface.cpp
18  *
19  * Created on: Dec 24, 2010
20  * Author: sumeet
21  */
22 
23 #include "ClientInterface.h"
24 
25 int ClientInterface::getLengthCl(string header,int size)
26 {
27  int totsize = header[size-1] & 0xff;
28  for (int var = 0; var < size-1; var++)
29  {
30  totsize |= ((header[var] & 0xff) << (size-1-var)*8);
31  }
32  return totsize;
33 }
34 
35 void* ClientInterface::get_in_addr(struct sockaddr *sa)
36 {
37  if (sa->sa_family == AF_INET) {
38  return &(((struct sockaddr_in*)sa)->sin_addr);
39  }
40  return &(((struct sockaddr_in6*)sa)->sin6_addr);
41 }
42 
43 int ClientInterface::create_tcp_socket()
44 {
45  int sock;
46  if((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
47  perror("Can't create TCP socket");
48  exit(1);
49  }
50  return sock;
51 }
52 char* ClientInterface::get_ip(char *host)
53 {
54  struct hostent *hent;
55  int iplen = 15; //XXX.XXX.XXX.XXX
56  char *ip = (char *)malloc(iplen+1);
57  memset(ip, 0, iplen+1);
58  if((hent = gethostbyname(host)) == NULL)
59  {
60  perror("Can't get IP");
61  return ip;
62  }
63  if(inet_ntop(AF_INET, (void *)hent->h_addr_list[0], ip, iplen) == NULL)
64  {
65  perror("Can't resolve host");
66  //return NULL;
67  }
68  return ip;
69 }
70 
71 bool ClientInterface::isConnected(int fd) {
72  char c;
73  if (recv(fd, &c, 1, MSG_DONTWAIT | MSG_PEEK) == 0) {
74  return false;
75  }
76  return true;
77 }