VB icon

Get Local Hostname and IP

Email
Submitted on: 8/22/2016 10:27:45 AM
By: Ben  
Level: Beginner
User Rating: Unrated
Compatibility: C++ (general), Microsoft Visual C++
Views: 1194
 
     Small code to allow you to find out your local hostname and local IP Address. Hope you like it.
 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
				
//**************************************
// Name: Get Local Hostname and IP
// Description:Small code to allow you to find out your local hostname and local IP Address.
Hope you like it.
// By: Ben
//**************************************

#pragma comment(lib, "Ws2_32.lib")
#include <iostream>
#include <winsock.h>
//Get Hostname & IP ~By DreammVB~
//Example of returning the local hostname and IP address.
using namespace std;
using std::cout;
using std::endl;
enum THostInfo{
	HOST_NAME = 0,
	HOST_IP = 1
};
string GetLocalHostInfo(THostInfo Opt){
	struct hostent *HostInfo;
	WSADATA WsData;
	char *StrIpAddr = NULL;
	char StrHostName[80];
	string RetVal = "";
	//Start up winsock
	if(WSAStartup(MAKEWORD(1,1),&WsData) != 0){
		return "";
	}
	//Get computer host name
	if(gethostname(StrHostName, sizeof(StrHostName)) == SOCKET_ERROR){
		return "";
	}
	//Get info
	HostInfo = gethostbyname(StrHostName);
	//Get the IP address of local host.
	StrIpAddr = inet_ntoa (*(struct in_addr *)*HostInfo->h_addr_list);
	switch(Opt){
		case HOST_NAME:
			//Return hostname
			RetVal = StrHostName;
			break;
		case HOST_IP:
			//Return IP
			RetVal = StrIpAddr;
			break;
		default:
			break;
	}
	//Clean up
	WSACleanup();
	memset(StrHostName,0,sizeof(StrHostName));
	//Return string
	return RetVal;
}
int main(int argc, char **anvg){
	//Print out local hostname and ip address.
	cout << "Hostname : " << GetLocalHostInfo(HOST_NAME).c_str() << endl;
	cout << "IP Address: " << GetLocalHostInfo(HOST_IP).c_str() << endl;
	//Keep console open
	system("pause");
	return 1;
}


Other 50 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Beginner category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.