Skip to content

Instantly share code, notes, and snippets.

@aneury1
Created November 29, 2017 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aneury1/451f310c603ee3973fddff5294de0c91 to your computer and use it in GitHub Desktop.
Save aneury1/451f310c603ee3973fddff5294de0c91 to your computer and use it in GitHub Desktop.
bool WinsockInitialized()
{
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET && WSAGetLastError() == WSANOTINITIALISED){
return false;
}
closesocket(s);
return true;
}
int init_socket_library_if_needed()
{
if( WinsockInitialized() == false)
{
WSAData wsa;
int res =-1;
res = WSAStartup(MAKEWORD(2,2), &wsa);
return res;
}
return 1;
}
void print_ip_address()
{
struct IPv4
{
unsigned char b1, b2, b3, b4;
};
IPv4 myIP;
char szBuffer[1024] ={'\0'};
if(gethostname(szBuffer, sizeof(szBuffer)) == SOCKET_ERROR)
{
#ifdef WIN32
WSACleanup();
#endif
}
struct hostent *host = gethostbyname(szBuffer);
if(host == NULL)
{
#ifdef WIN32
WSACleanup();
#endif
}
//Obtain the computer's IP
myIP.b1 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b1;
myIP.b2 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b2;
myIP.b3 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b3;
myIP.b4 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b4;
cout <<" Waiting for Conection at : "<< (int)myIP.b1<<"."<<(int) myIP.b2<<"."<<(int)myIP.b3<<"."<<(int)myIP.b4<<endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment