Skip to content

Commit

Permalink
reuse some code
Browse files Browse the repository at this point in the history
  • Loading branch information
puritys committed May 24, 2015
1 parent 50c3716 commit a787145
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 15 deletions.
13 changes: 13 additions & 0 deletions src/cpp/socket/src/socket.cc
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
#include "socket.h"
#include <stdio.h>

sockaddr_in getSocketAddr(char *hostname, int port) {
struct sockaddr_in serv_addr;
struct hostent *hPtr;
hPtr = gethostbyname(hostname);
memcpy((char *)&serv_addr.sin_addr, hPtr->h_addr, hPtr->h_length);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
return serv_addr;
}

#ifdef OS_LINUX
#include "socket_linux.cc"
Expand All @@ -8,3 +19,5 @@
#include "socket_win.cc"
#endif



3 changes: 3 additions & 0 deletions src/cpp/socket/src/socket.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
#endif

#ifdef OS_WIN
#include <winsock2.h>
#include <iostream>
using namespace std;
#endif


Expand Down
2 changes: 0 additions & 2 deletions src/cpp/socket/src/socket_linux.cc
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#include "socket.h"
#include <stdio.h>

//http://linux.die.net/man/2/socket
int phplikeSocketConnect(char *hostname, int port) {/*{{{*/
Expand Down
16 changes: 3 additions & 13 deletions src/cpp/socket/src/socket_win.cc
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
#include <iostream>
#include "stdio.h"
#include <winsock2.h>

using namespace std;
// http://blog.pusheax.com/2013/07/windows-api-winsock-create-your-first.html
int phplikeSocketConnect(char *hostname, int port) {/*{{{*/
struct hostent *hPtr;
struct sockaddr_in serv_addr;

WSAData version; //We need to check the version.
WSAData version;
WORD mkword = MAKEWORD(2,2);
int what = WSAStartup(mkword,&version);
if(what!=0) {
Expand All @@ -20,14 +15,9 @@ int phplikeSocketConnect(char *hostname, int port) {/*{{{*/
std::cout<<"Creating socket fail\n";
}

hPtr = gethostbyname(hostname);
memcpy((char *)&serv_addr.sin_addr, hPtr->h_addr, hPtr->h_length);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
/*==========Addressing finished==========*/
serv_addr = getSocketAddr(hostname, port);

//Now we connect
int conn=connect(u_sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
int conn = connect(u_sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
if (conn == SOCKET_ERROR) {
std::cout<<"Error - when connecting "<<WSAGetLastError()<<std::endl;
closesocket(u_sock);
Expand Down

0 comments on commit a787145

Please sign in to comment.