VB icon

Get Local Hostname and IP

Submitted on: 8/22/2016 10:27:45 AM
By: Ben128  
Level: Beginner
User Rating: Unrated
Compatibility: C++ (general), Microsoft Visual C++
Views: 1818
     Small code to allow you to find out your local hostname and local IP Address. Hope you like it.
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: Ben128

#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_IP = 1
string GetLocalHostInfo(THostInfo Opt){
	struct hostent *HostInfo;
	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);
		case HOST_NAME:
			//Return hostname
			RetVal = StrHostName;
		case HOST_IP:
			//Return IP
			RetVal = StrIpAddr;
	//Clean up
	//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
	return 1;

Other 51 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.